﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using System.IO.Ports;
using SerialPortHelperLib;
using System.Drawing.Drawing2D;
using System.Threading;
using XChipTool.Enties;
using System.Configuration;
using XChip_Common;
using BinAnalysisHelp;
using AdbService;

namespace XChipTool
{
    public partial class XChip_AE : DevExpress.XtraEditors.XtraUserControl
    {

        public SerialPort sPortTemp;
        private bool isRead = false;
        private KeyEventArgs keyEnter = new KeyEventArgs(Keys.Enter);//用来手动触发文本框下发配置
        private long[] m_nFollowArea = new long[8];
        private bool isWrite = false;
        private addressregisterManager aBll;
        private List<addressregister> XChipAe;

        List<string> listFiltration = new List<string> { "AE_WIDTH", "AE_HEIGHT", "AE_WIN_WIDTH_X", "AE_WIN_HEIGHT_Y", "AE_WIN_WIDTH", "AE_WIN_HEIGHT" };
        //记录是否使用USB设备读写
        public bool IsUsbOpen = false;
        //记录是否使用I2C设备读写
        public bool m_open = false;

        private static XChip_AE _instance;


        // 使用服务定位器获取ADB服务
        private IAdbCommandService adbService = ServiceLocator.AdbCommandService;

        public static XChip_AE Instance(SerialPort _sPortTemp, addressregisterManager _aBll)
        {
            if (_instance == null)
            {
                _instance = new XChip_AE(_sPortTemp, _aBll);
            }
            return _instance;
        }

        public XChip_AE()
        {
            InitializeComponent();
        }
        public XChip_AE(SerialPort _sPortTemp, addressregisterManager _aBll)
        {
            sPortTemp = _sPortTemp;
            aBll = _aBll;
            XChipAe = aBll.GetList(c => c.ChipType == ConfigurationManager.AppSettings["xc151_ChipType"] && (c.Classify == "ae" || c.Classify == "Common"));
            InitializeComponent();
        }
        private Control[] Controls_Find(string str)
        {
            //var t =   this.Controls.Find(type, true);
            List<Control> listc = new List<Control>();
            System.Reflection.FieldInfo[] fieldInfo = this.GetType().GetFields(System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
            for (int i = 0; i < fieldInfo.Length; i++)
            {
                if (fieldInfo[i].Name.ToLower().Contains(str.ToLower()))
                {
                    listc.AddRange(this.Controls.Find(fieldInfo[i].Name, true));
                    break;
                }
            }
            return listc.ToArray();
        }

        private async void simpleButton5_Click(object sender, EventArgs e)
        {
           
            //ulong nDaymode = 0;
            isRead = true;
            WaitBefore.Start("读取中", "正在加载中", 10);
           await  GetISPAeSetting();

        }


        #region ADB异步读写


        /// <summary>
        /// 异步读取单个寄存器并更新文本框
        /// </summary>
        private async Task ReadRegisterAndUpdateTextAsync(string address, TextEdit textEdit, string bits, string hex)
        {
            try
            {
                string val = (await ReadRegisterAsync(address)).ToString("X");
                textEdit.Text = BitsHelp.GetBitsToUint(bits, hex, val).ToString("X");
            }
            catch (Exception ex)
            {
                // 处理异常
                textEdit.Text = "Error";
            }
        }

        /// <summary>
        /// 异步读取多个寄存器并组合更新文本框
        /// </summary>
        private async Task ReadMultipleRegistersAndUpdateTextAsync(List<addressregister> nList, TextEdit textEdit, long nMask, int selectedIndex)
        {
            try
            {
                // 特殊处理逻辑 - 根据寄存器类型进行筛选
                if (nList.Exists(c => c.NameType.ToLower().Contains("ae_target_judge_tab")))
                {
                    nList = nList.Where(c => c.NameType.ToLower().Contains(selectedIndex == 0 ? "_day" : "_night") && !c.NameType.ToLower().Contains("_set")).ToList();
                }
                else if (nList.Exists(c => c.NameType.ToLower().Contains("ae_target_judge_thr")))
                {
                    nList = nList.Where(c => c.NameType.ToLower().Contains(selectedIndex == 0 ? "_day" : "_night") && !c.NameType.ToLower().Contains("_set")).ToList();
                }
                else if (nList.Exists(c => c.NameType.ToLower().Contains("ae_weight") ||
                        c.NameType.ToLower().Contains("start_blk") ||
                        c.NameType.ToLower().Contains("blk_num")))
                {
                    if (nMask == 0)
                    {
                        nList = nList.Where(c => c.NameType.ToLower() == textEdit.Name.ToLower()).ToList();
                    }
                    else
                    {
                        nMask = await GetAERegister("Scene_Mode");
                        nMask &= 0x3;
                        if (nMask == 0)
                        {
                            nList = nList.Where(c => c.NameType.ToLower().Contains("_day")).ToList();
                        }
                        else if (nMask == 1)
                        {
                            nList = nList.Where(c => c.NameType.ToLower().Contains("_night")).ToList();
                        }
                        else
                        {
                            nList = nList.Where(c => c.NameType.ToLower().Contains("_midnight")).ToList();
                        }
                    }
                }
                else if (nList.Exists(c => c.NameType.ToLower().Contains("ae_win_width") ||
                        c.NameType.ToLower().Contains("ae_win_height")))
                {
                    if (nMask == 0)
                    {
                        nList = nList.Where(c => c.NameType.ToLower() == $"{textEdit.Name.ToLower()}_h" || c.NameType.ToLower() == $"{textEdit.Name.ToLower()}_l").ToList();
                    }
                    else
                    {
                        nMask = await GetAERegister("Scene_Mode");
                        nMask &= 0x3;
                        if (nMask == 0)
                        {
                            nList = nList.Where(c => c.NameType.ToLower() == $"{textEdit.Name.ToLower()}_h_day" || c.NameType.ToLower() == $"{textEdit.Name.ToLower()}_l_day").ToList();
                        }
                        else if (nMask == 1)
                        {
                            nList = nList.Where(c => c.NameType.ToLower() == $"{textEdit.Name.ToLower()}_h_night" || c.NameType.ToLower() == $"{textEdit.Name.ToLower()}_l_night").ToList();
                        }
                        else
                        {
                            nList = nList.Where(c => c.NameType.ToLower() == $"{textEdit.Name.ToLower()}_h_midnight" || c.NameType.ToLower() == $"{textEdit.Name.ToLower()}_l_midnight").ToList();
                        }
                    }
                }

                string val = string.Empty;

                // 多个寄存器组合读取
                if (nList.Exists(c => c.NameType.ToLower().Contains("_h")))
                {
                    val += (await ReadRegisterAsync(nList.Find(c => c.NameType.ToLower().Contains("_h")).Address)).ToString("X2");
                }

                if (nList.Exists(c => c.NameType.ToLower().Contains("_m2")))
                {
                    val += (await ReadRegisterAsync(nList.Find(c => c.NameType.ToLower().Contains("_m2")).Address)).ToString("X2");
                }
                if (nList.Exists(c => c.NameType.ToLower().Contains("_m1")))
                {
                    val += (await ReadRegisterAsync(nList.Find(c => c.NameType.ToLower().Contains("_m1")).Address)).ToString("X2");
                }
                if (nList.Exists(c => c.NameType.ToLower().Contains("_m0")))
                {
                    val += (await ReadRegisterAsync(nList.Find(c => c.NameType.ToLower().Contains("_m0")).Address)).ToString("X2");
                }
                if (nList.Exists(c => c.NameType.ToLower().Contains("_l")))
                {
                    if (nList.Exists(c => c.NameType.ToLower().Substring(c.NameType.Length - 2).Contains("_l")))
                    {
                        val += (await ReadRegisterAsync(nList.Find(c => c.NameType.ToLower().Substring(c.NameType.Length - 2).Contains("_l")).Address)).ToString("X2");
                    }
                    else
                    {
                        val += (await ReadRegisterAsync(nList.Last(c => c.NameType.ToLower().Contains("_l")).Address)).ToString("X2");
                    }
                }

                // 特殊处理：如果是ae_weight寄存器，调用setLabTxtJiu
                if (nList.Count == 1 && nList[0].NameType.ToLower().Contains("ae_weight"))
                {
                    var nameArr = nList[0].NameType.Split('_');
                    string singleVal = (await ReadRegisterAsync(nList[0].Address)).ToString("X");
                    setLabTxtJiu(int.Parse(nameArr.Last()) - 1, singleVal);
                    textEdit.Text = BitsHelp.GetBitsToUint(nList[0].Bits, nList[0].Hex, singleVal).ToString("X");
                }
                else if (listFiltration.Exists(c => c == textEdit.Name.ToString()))
                {
                    textEdit.Text = Convert.ToInt32(val, 16).ToString();
                }
                else
                {
                    textEdit.Text = val;
                }
            }
            catch (Exception ex)
            {
                textEdit.Text = "Error";
            }
        }
        /// <summary>
        /// 根据优先级查找寄存器
        /// </summary>
        private addressregister FindRegisterByPriority(List<addressregister> nList, string priority)
        {
            if (priority == "_l")
            {
                // 特殊处理 _l 寄存器
                if (nList.Exists(c => c.NameType.ToLower().Contains("_l")))
                {
                    // 首先查找以 "_l" 结尾的寄存器
                    var exactMatch = nList.Find(c => c.NameType.ToLower().EndsWith("_l"));
                    if (exactMatch != null)
                    {
                        Console.WriteLine($"[ADBForm] 找到以 '_l' 结尾的寄存器: {exactMatch.NameType}");
                        return exactMatch;
                    }
                    else
                    {
                        // 如果没有以 "_l" 结尾的，则使用最后一个包含 "_l" 的寄存器
                        var containsMatch = nList.Last(c => c.NameType.ToLower().Contains("_l"));
                        Console.WriteLine($"[ADBForm] 找到包含 '_l' 的寄存器: {containsMatch.NameType}");
                        return containsMatch;
                    }
                }
            }
            else
            {
                // 其他寄存器正常处理
                var register = nList.Find(c => c.NameType.ToLower().Contains(priority));
                if (register != null)
                {
                    Console.WriteLine($"[ADBForm] 找到包含 '{priority}' 的寄存器: {register.NameType}");
                    return register;
                }
            }

            return null;
        }

        /// <summary>
        /// 更新文本框的辅助方法
        /// </summary>
        private void UpdateTextEdit(TextEdit textEdit, string value)
        {
            if (textEdit.InvokeRequired)
            {
                textEdit.Invoke(new Action(() =>
                {
                    textEdit.Text = value;
                    Console.WriteLine($"[ADBForm] UI已更新，文本框值: {value}");
                }));
            }
            else
            {
                textEdit.Text = value;
                Console.WriteLine($"[ADBForm] UI已更新，文本框值: {value}");
            }
        }

        /// <summary>
        /// 异步读取寄存器并更新复选框
        /// </summary>
        private async Task ReadRegisterAndUpdateCheckAsync(string address, CheckEdit checkEdit, string bits, string hex)
        {
            try
            {
                string val = (await ReadRegisterAsync(address)).ToString("X");
                checkEdit.Checked = BitsHelp.GetBitsCheckedToBool(bits, hex, val) == 0;
            }
            catch (Exception ex)
            {
                // 处理异常
                checkEdit.CheckState = CheckState.Unchecked;
            }
        }

        /// <summary>
        /// 异步读取单个寄存器返回值
        /// </summary>
        private async Task<long> ReadRegisterAsync(string address)
        {
            try
            {
                Console.WriteLine($"[ADBForm] 开始读取寄存器: {address}");
                // 发送读取命令
                string adbCommand = $"adb shell setprop vendor.extcamera.xxw.ispregctrl \"0,{address},0,0\"";
                await adbService.ExecuteAdbCommandAsync(adbCommand, $"读操作 - 地址:{address}");

                // 等待命令执行
                await Task.Delay(10);

                // 获取寄存器值
                var record = await Task.Run(() => LogcatDataManager.FindByRegisterAddressSync(address, "Read", 500));

                if (record != null && !string.IsNullOrEmpty(record.Values) && record.Values != "0")
                {
                    return Convert.ToInt32(record.Values, 16);
                }
                else
                {
                    Console.WriteLine($"[ADBForm] 读取寄存器 {address} 失败，值为空或0，使用默认值0");
                    return 0;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"[ADBForm] 读取寄存器 {address} 异常: {ex.Message}");
                return 0;
            }
        }
        /// <summary>
        /// 异步写入单个寄存器，在值不匹配时自动重试一次
        /// </summary>
        private async Task<bool> WriteRegisterAsync(string address, string value)
        {
            int maxRetries = 1; // 值不匹配时最多重试一次
            int retryCount = 0;

            while (retryCount <= maxRetries)
            {
                try
                {
                    if (retryCount > 0)
                    {
                        Console.WriteLine($"[ADBForm] 第 {retryCount} 次重试写入寄存器: {address} 值: {value}");
                    }
                    else
                    {
                        Console.WriteLine($"[ADBForm] 开始写入寄存器: {address} 值: {value}");
                    }

                    // 处理位操作（如果有）
                    string processedValue = value;

                    // 确保值是十六进制格式（不带0x前缀）
                    if (processedValue.StartsWith("0x"))
                    {
                        processedValue = processedValue.Substring(2);
                    }

                    // 发送写入命令
                    string adbCommand = $"adb shell setprop vendor.extcamera.xxw.ispregctrl \"1,{address},{processedValue},0\"";
                    adbService.ExecuteAdbCommandAsync(adbCommand, $"写操作 - 地址:{address} 值:{processedValue}");

                    // 等待命令执行
                    await Task.Delay(10);

                    // 验证写入是否成功 - 等待写入记录出现
                    var writeRecord = await Task.Run(() => LogcatDataManager.FindByRegisterAddressSync(address, "Write", 500));

                    if (writeRecord != null && !string.IsNullOrEmpty(writeRecord.Values))
                    {
                        string actualValue = writeRecord.Values;
                        if (actualValue.StartsWith("0x"))
                        {
                            actualValue = actualValue.Substring(2);
                        }

                        // 比较写入的值是否匹配
                        bool success = string.Equals(actualValue, processedValue, StringComparison.OrdinalIgnoreCase);

                        if (success)
                        {
                            Console.WriteLine($"[ADBForm] 成功写入寄存器 {address} 值: {processedValue}");
                            return true;
                        }
                        else
                        {
                            Console.WriteLine($"[ADBForm] 写入寄存器 {address} 值不匹配，期望: {processedValue}，实际: {actualValue}");

                            // 如果不匹配且还有重试次数，则继续重试
                            if (retryCount < maxRetries)
                            {
                                retryCount++;
                                Console.WriteLine($"[ADBForm] 准备重试写入...");
                                continue; // 直接进入下一次循环，重新发送命令
                            }
                            else
                            {
                                Console.WriteLine($"[ADBForm] 写入寄存器 {address} 重试次数已用完，仍然不匹配");
                                return false;
                            }
                        }
                    }
                    else
                    {
                        Console.WriteLine($"[ADBForm] 写入寄存器 {address} 失败，未找到写入确认记录");

                        // 如果未找到记录且还有重试次数，则重试
                        if (retryCount < maxRetries)
                        {
                            retryCount++;
                            Console.WriteLine($"[ADBForm] 准备重试写入...");
                            continue;
                        }
                        else
                        {
                            return false;
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"[ADBForm] 写入寄存器 {address} 异常: {ex.Message}");

                    // 如果异常且还有重试次数，则重试
                    if (retryCount < maxRetries)
                    {
                        retryCount++;
                        Console.WriteLine($"[ADBForm] 准备重试写入...");
                        await Task.Delay(10); // 异常后稍作延迟再重试
                        continue;
                    }
                    else
                    {
                        return false;
                    }
                }
            }

            return false; // 理论上不会执行到这里
        }




        #endregion





        public async Task GetISPAeSetting()
        {
            #region 勾选框获取

            try
            {
                if ((await GetAERegister("Mono_mode_en") & 0x80) == 0x80)
                {
                    Mode_switch.SelectedIndex = 1;
                }
                else
                {
                    Mode_switch.SelectedIndex = 0;
                }

                // 只读取一次 Target_switch 寄存器
                var targetSwitchValue = await GetAERegister("Target_switch");

                if (targetSwitchValue == 0)
                {
                    COMBO_GAMMAPRE.ItemIndex = 0;
                    TargetSwitchEnShowHide(false);
                }
                else if (targetSwitchValue == 1)
                {
                    COMBO_GAMMAPRE.ItemIndex = 1;
                    TargetSwitchEnShowHide(true);
                }
                else if (targetSwitchValue == 2)
                {
                    COMBO_GAMMAPRE.ItemIndex = 2;
                    TargetSwitchEnShowHide(true);
                }
                else
                {
                    COMBO_GAMMAPRE.ItemIndex = -1;
                }

                var WEIGHTENABLE_EN = (await GetAERegister("AE_WEIGHTENABLE_EN")) & 0x01;
                long newmode_en = 0;

                newmode_en = ((await ReadRegisterAsync("2000023f")) & 0x01);

                if (newmode_en == 1)
                {
                    Newmode_en.CheckState = CheckState.Checked;
                }
                else
                {
                    Newmode_en.CheckState = CheckState.Unchecked;
                }

                if (WEIGHTENABLE_EN == 1)
                {
                    AE_WEIGHTENABLE_EN.CheckState = CheckState.Checked;
                }
                else
                {
                    AE_WEIGHTENABLE_EN.CheckState = CheckState.Unchecked;
                }

                string scenesMask = Mode_switch.EditValue.ToString() == "1" ? "_Day" : "_Night";
                long nMask = 0;
                nMask = (await GetAERegister("Scene_Switch_En"));

                // 记录开始时间和寄存器计数
                var startTime = DateTime.Now;
                int totalRegisterCount = 0;
                List<string> NameList = new List<string>();

                for (int i = 0; i < XChipAe.Count; i++)
                {
                    var type = AppHelper.NameTypeToString(XChipAe[i].NameType);
                    if (NameList.Exists(c => c.ToLower().Contains(type)))
                    {
                        continue;
                    }
                    if (XChipAe[i].NameType.Contains("AE_WEIGHT_") && !XChipAe[i].NameType.Contains("_EN"))
                    {
                        continue;
                    }

                    try
                    {
                        var col = Controls_Find(type);
                        foreach (var item in col)
                        {
                            if (item is TextEdit)
                            {
                                item.Text = "";
                                var nList = XChipAe.Where(c => c.NameType.ToLower().Contains(item.Name.ToString().ToLower()) && c.ControlType == "0").ToList();

                                if (nList.Count == 0)
                                {
                                    nList = XChipAe.Where(c => c.NameType.ToLower().Contains(item.Name.ToString().ToLower()) && c.ControlType == "0").ToList();
                                }

                                if (nList.Count == 1)
                                {
                                    // 单个寄存器读取
                                    var address = nList[0].Address;
                                    totalRegisterCount++;
                                    await ReadRegisterAndUpdateTextAsync(address, item as TextEdit, nList[0].Bits, nList[0].Hex);
                                }
                                else
                                {
                                    // 多个寄存器组合读取 - 特殊处理逻辑
                                    totalRegisterCount += nList.Count;
                                    await ReadMultipleRegistersAndUpdateTextAsync(nList, item as TextEdit, nMask, Mode_switch.SelectedIndex);
                                }
                            }
                            else if (item is CheckEdit)
                            {
                                var nList = XChipAe.Where(c => c.NameType.ToLower().Contains(item.Name.ToString().ToLower()) && c.ControlType == "1").ToList();
                                if (nList.Count == 1)
                                {
                                    var address = nList[0].Address;
                                    totalRegisterCount++;
                                    await ReadRegisterAndUpdateCheckAsync(address, item as CheckEdit, nList[0].Bits, nList[0].Hex);
                                }
                            }
                       
                        
                        }

                        //ae_win_width\ae_win_height 重复名称太多 这里不过滤 数据进行强匹配
                        if (type.ToLower().Contains("ae_win_width") || type.ToLower().Contains("ae_win_height"))
                        {
                            continue;
                        }
                        NameList.Add(type);
                    }
                    catch (Exception)
                    {
                        continue;
                    }
                }

                //这个测光窗口只读写20000078开始的这组寄存器
                for (int i = 0; i < 64; i++)
                {
                    var nTemp = await GetAERegister($"AE_WEIGHT_{(i + 1).ToString("D2")}");
                    SetAEWin(i, nTemp);
                }

                var nValue = await GetAERegister("Flicker5060SW");
                if (nValue == 0) //disable
                {
                    checkedListBoxControl2.Items[0].CheckState = CheckState.Unchecked;
                    checkedListBoxControl2.Items[1].CheckState = CheckState.Unchecked;
                }
                else if (nValue == 1) //60hz
                {
                    checkedListBoxControl2.Items[0].CheckState = CheckState.Unchecked;
                    checkedListBoxControl2.Items[1].CheckState = CheckState.Checked;
                }
                else if (nValue == 2) //50hz
                {
                    checkedListBoxControl2.Items[0].CheckState = CheckState.Checked;
                    checkedListBoxControl2.Items[1].CheckState = CheckState.Unchecked;
                }
                #endregion

                //aewinTxt.Text = $"{AE_WIN_WIDTH.Text} x {AE_WIN_HEIGHT.Text}";

                //显示ae窗体文本值
                #region 目标亮度 增益 曝光行的读
                AE_SpeedModeradio.SelectedIndex = ((int)await ReadRegisterAsync(XChipAe.Find(c => c.NameType.ToLower().Contains("speed_mode_man".ToLower()) && c.ControlType == "0").Address));
                #endregion

                m_nFollowArea[0] = await ReadRegisterAsync("200000b8");
                m_nFollowArea[1] = await ReadRegisterAsync("200000b9");
                m_nFollowArea[2] = await ReadRegisterAsync("200000ba");
                m_nFollowArea[3] = await ReadRegisterAsync("200000bb");
                m_nFollowArea[4] = await ReadRegisterAsync("200000bc");
                m_nFollowArea[5] = await ReadRegisterAsync("200000bd");
                m_nFollowArea[6] = await ReadRegisterAsync("200000be");
                m_nFollowArea[7] = await ReadRegisterAsync("200000bf");

                CheckFollowArea(m_nFollowArea);
                AE_FOLLOW_AREA.Text = (m_nFollowArea[7] << 56 | m_nFollowArea[6] << 48 | m_nFollowArea[5] << 40 | m_nFollowArea[4] << 32 | m_nFollowArea[3] << 24 | m_nFollowArea[2] << 16 | m_nFollowArea[1] << 8 | m_nFollowArea[0]).ToString("X15");

                simpleButton1_Click(null, null);//Cur_scene Get
                isRead = true;
                simpleButton3_Click(null, null);//Final_cal Get
                isRead = false;

                if (speed_mode_man_en.Checked)
                {
                   await  SetAeRegister("speed_mode_man", 0x01);
                }
                EnShowHide();
            }
            catch (Exception)
            {
            }
            finally
            {
                isRead = false;
                WaitBefore.Close();
            }
        }



        private void SetAEWin(int i, long nTemp)
        {
            foreach (Control item in panelControl5.Controls)
            {
                if (item is TextEdit)
                {
                    if (item.Name == $"AE_WEIGHT_{(i + 1).ToString("D2")}")
                    {
                        item.Text = (nTemp & 0x7F).ToString("X2");
                    }
                }
            }
        }
        void CheckFollowArea(long[] m_nFollowArea)
        {
            AE_WT_0_EN.Checked = (m_nFollowArea[0] & 1) == 1 ? true : false;
            AE_WT_1_EN.Checked = (m_nFollowArea[0] & 2) >> 1 == 1 ? true : false;
            AE_WT_2_EN.Checked = ((m_nFollowArea[0] & 4) >> 2) == 1 ? true : false;
            AE_WT_3_EN.Checked = (m_nFollowArea[0] & 8) >> 3 == 1 ? true : false;
            AE_WT_4_EN.Checked = (m_nFollowArea[0] & 16) >> 4 == 1 ? true : false;
            AE_WT_5_EN.Checked = (m_nFollowArea[0] & 32) >> 5 == 1 ? true : false;
            AE_WT_6_EN.Checked = (m_nFollowArea[0] & 64) >> 6 == 1 ? true : false;
            AE_WT_7_EN.Checked = (m_nFollowArea[0] & 128) >> 7 == 1 ? true : false;

            AE_WT_8_EN.Checked = (m_nFollowArea[1] & 1) == 1 ? true : false;
            AE_WT_9_EN.Checked = (m_nFollowArea[1] & 2) >> 1 == 1 ? true : false;
            AE_WT_10_EN.Checked = (m_nFollowArea[1] & 4) >> 2 == 1 ? true : false;
            AE_WT_11_EN.Checked = (m_nFollowArea[1] & 8) >> 3 == 1 ? true : false;
            AE_WT_12_EN.Checked = (m_nFollowArea[1] & 16) >> 4 == 1 ? true : false;
            AE_WT_13_EN.Checked = (m_nFollowArea[1] & 32) >> 5 == 1 ? true : false;
            AE_WT_14_EN.Checked = (m_nFollowArea[1] & 64) >> 6 == 1 ? true : false;
            AE_WT_15_EN.Checked = (m_nFollowArea[1] & 128) >> 7 == 1 ? true : false;

            AE_WT_16_EN.Checked = (m_nFollowArea[2] & 1) == 1 ? true : false;
            AE_WT_17_EN.Checked = (m_nFollowArea[2] & 2) >> 1 == 1 ? true : false;
            AE_WT_18_EN.Checked = (m_nFollowArea[2] & 4) >> 2 == 1 ? true : false;
            AE_WT_19_EN.Checked = (m_nFollowArea[2] & 8) >> 3 == 1 ? true : false;
            AE_WT_20_EN.Checked = (m_nFollowArea[2] & 16) >> 4 == 1 ? true : false;
            AE_WT_21_EN.Checked = (m_nFollowArea[2] & 32) >> 5 == 1 ? true : false;
            AE_WT_22_EN.Checked = (m_nFollowArea[2] & 64) >> 6 == 1 ? true : false;
            AE_WT_23_EN.Checked = (m_nFollowArea[2] & 128) >> 7 == 1 ? true : false;

            AE_WT_24_EN.Checked = (m_nFollowArea[3] & 1) == 1 ? true : false;
            AE_WT_25_EN.Checked = (m_nFollowArea[3] & 2) >> 1 == 1 ? true : false;
            AE_WT_26_EN.Checked = (m_nFollowArea[3] & 4) >> 2 == 1 ? true : false;
            AE_WT_27_EN.Checked = (m_nFollowArea[3] & 8) >> 3 == 1 ? true : false;
            AE_WT_28_EN.Checked = (m_nFollowArea[3] & 16) >> 4 == 1 ? true : false;
            AE_WT_29_EN.Checked = (m_nFollowArea[3] & 32) >> 5 == 1 ? true : false;
            AE_WT_30_EN.Checked = (m_nFollowArea[3] & 64) >> 6 == 1 ? true : false;
            AE_WT_31_EN.Checked = (m_nFollowArea[3] & 128) >> 7 == 1 ? true : false;

            AE_WT_32_EN.Checked = (m_nFollowArea[4] & 1) == 1 ? true : false;
            AE_WT_33_EN.Checked = (m_nFollowArea[4] & 2) >> 1 == 1 ? true : false;
            AE_WT_34_EN.Checked = (m_nFollowArea[4] & 4) >> 2 == 1 ? true : false;
            AE_WT_35_EN.Checked = (m_nFollowArea[4] & 8) >> 3 == 1 ? true : false;
            AE_WT_36_EN.Checked = (m_nFollowArea[4] & 16) >> 4 == 1 ? true : false;
            AE_WT_37_EN.Checked = (m_nFollowArea[4] & 32) >> 5 == 1 ? true : false;
            AE_WT_38_EN.Checked = (m_nFollowArea[4] & 64) >> 6 == 1 ? true : false;
            AE_WT_39_EN.Checked = (m_nFollowArea[4] & 128) >> 7 == 1 ? true : false;

            AE_WT_40_EN.Checked = (m_nFollowArea[5] & 1) == 1 ? true : false;
            AE_WT_41_EN.Checked = (m_nFollowArea[5] & 2) >> 1 == 1 ? true : false;
            AE_WT_42_EN.Checked = (m_nFollowArea[5] & 4) >> 2 == 1 ? true : false;
            AE_WT_43_EN.Checked = (m_nFollowArea[5] & 8) >> 3 == 1 ? true : false;
            AE_WT_44_EN.Checked = (m_nFollowArea[5] & 16) >> 4 == 1 ? true : false;
            AE_WT_45_EN.Checked = (m_nFollowArea[5] & 32) >> 5 == 1 ? true : false;
            AE_WT_46_EN.Checked = (m_nFollowArea[5] & 64) >> 6 == 1 ? true : false;
            AE_WT_47_EN.Checked = (m_nFollowArea[5] & 128) >> 7 == 1 ? true : false;

            AE_WT_48_EN.Checked = (m_nFollowArea[6] & 1) == 1 ? true : false;
            AE_WT_49_EN.Checked = (m_nFollowArea[6] & 2) >> 1 == 1 ? true : false;
            AE_WT_50_EN.Checked = (m_nFollowArea[6] & 4) >> 2 == 1 ? true : false;
            AE_WT_51_EN.Checked = (m_nFollowArea[6] & 8) >> 3 == 1 ? true : false;
            AE_WT_52_EN.Checked = (m_nFollowArea[6] & 16) >> 4 == 1 ? true : false;
            AE_WT_53_EN.Checked = (m_nFollowArea[6] & 32) >> 5 == 1 ? true : false;
            AE_WT_54_EN.Checked = (m_nFollowArea[6] & 64) >> 6 == 1 ? true : false;
            AE_WT_55_EN.Checked = (m_nFollowArea[6] & 128) >> 7 == 1 ? true : false;

            AE_WT_56_EN.Checked = (m_nFollowArea[7] & 1) == 1 ? true : false;
            AE_WT_57_EN.Checked = (m_nFollowArea[7] & 2) >> 1 == 1 ? true : false;
            AE_WT_58_EN.Checked = (m_nFollowArea[7] & 4) >> 2 == 1 ? true : false;
            AE_WT_59_EN.Checked = (m_nFollowArea[7] & 8) >> 3 == 1 ? true : false;
            AE_WT_60_EN.Checked = (m_nFollowArea[7] & 16) >> 4 == 1 ? true : false;
            AE_WT_61_EN.Checked = (m_nFollowArea[7] & 32) >> 5 == 1 ? true : false;
            AE_WT_62_EN.Checked = (m_nFollowArea[7] & 64) >> 6 == 1 ? true : false;
            AE_WT_63_EN.Checked = (m_nFollowArea[7] & 128) >> 7 == 1 ? true : false;
        }
        void TargetSwitchEnShowHide(bool isbool)
        {
            AE_BRIGHTNESS.Enabled = !isbool;
            Factor.Enabled = isbool;
            AE_TARGET_JUDGE_TAB0.Enabled = isbool;
            AE_TARGET_JUDGE_TAB1.Enabled = isbool;
            AE_TARGET_JUDGE_TAB2.Enabled = isbool;
            AE_TARGET_JUDGE_TAB3.Enabled = isbool;
            AE_TARGET_JUDGE_TAB4.Enabled = isbool;
            AE_TARGET_JUDGE_TAB5.Enabled = isbool;
            AE_TARGET_JUDGE_THR0.Enabled = isbool;
            AE_TARGET_JUDGE_THR1.Enabled = isbool;
            AE_TARGET_JUDGE_THR2.Enabled = isbool;
            AE_TARGET_JUDGE_THR3.Enabled = isbool;
            AE_TARGET_JUDGE_THR4.Enabled = isbool;

        }

        void GetTargetJudgeTable(long dayValue, int index)
        {
            switch (index)
            {
                case 0:
                    AE_TARGET_JUDGE_TAB0.Text = dayValue.ToString("X2");

                    break;
                case 1:
                    AE_TARGET_JUDGE_TAB1.Text = dayValue.ToString("X2");

                    break;
                case 2:
                    AE_TARGET_JUDGE_TAB2.Text = dayValue.ToString("X2");

                    break;
                case 3:
                    AE_TARGET_JUDGE_TAB3.Text = dayValue.ToString("X2");

                    break;
                case 4:
                    AE_TARGET_JUDGE_TAB4.Text = dayValue.ToString("X2");

                    break;
                case 5:
                    AE_TARGET_JUDGE_TAB5.Text = dayValue.ToString("X2");

                    break;
                default:
                    break;
            }
        }

        void GetTargetJudgeThr(long Value, int index)
        {
            switch (index)
            {
                case 0:
                    AE_TARGET_JUDGE_THR0.Text = Value.ToString("X2");

                    break;
                case 1:
                    AE_TARGET_JUDGE_THR1.Text = Value.ToString("X2");

                    break;
                case 2:
                    AE_TARGET_JUDGE_THR2.Text = Value.ToString("X2");

                    break;
                case 3:
                    AE_TARGET_JUDGE_THR3.Text = Value.ToString("X2");

                    break;
                case 4:
                    AE_TARGET_JUDGE_THR4.Text = Value.ToString("X2");

                    break;
                default:
                    break;
            }
        }


        //final _cal获取
        private async void simpleButton3_Click(object sender, EventArgs e)
        {
            
            isRead = true;
            try
            {
                var nBHigh = await GetAERegister("Factor_h");
                var nHigh = await GetAERegister("Factor_m1");
                var nMid = await GetAERegister("Factor_m0");
                var nLow = await GetAERegister("Factor_l");
                var factor = (nBHigh << 24) | (nHigh << 16) | (nMid << 8) | (nLow); //factor


                Factor.Text = factor.ToString("X2");

                nHigh = await GetAERegister("AE_BRIGHTNESS_h");
                nLow = await GetAERegister("AE_BRIGHTNESS_l");

                AE_BRIGHTNESS.Text = ((nHigh << 8 & 0xff00) | (nLow & 0xff)).ToString("X4");

                nHigh = await GetAERegister("AE_AVRBIRGHT_h");
                nLow = await GetAERegister("AE_AVRBIRGHT_l");

                var ae_avrbight = (nHigh << 8 & 0xff00) | (nLow & 0xff);//ae_avrbight            
                nBHigh = await GetAERegister("AE_EDIT_GAIN_h");
                nHigh = await GetAERegister("AE_EDIT_GAIN_m0");
                nMid = await GetAERegister("AE_EDIT_GAIN_m1");
                nLow = await GetAERegister("AE_EDIT_GAIN_l");

                var ae_edit_gain = ((nBHigh << 24) | (nHigh << 16) | (nMid << 8) | nLow);//ae_edit_gain

                nBHigh = await GetAERegister("AE_EDIT_EXPLINE_h");
                nHigh = await GetAERegister("AE_EDIT_EXPLINE_m0");
                nMid = await GetAERegister("AE_EDIT_EXPLINE_m1");
                nLow = await GetAERegister("AE_EDIT_EXPLINE_l");
                //nHigh = GetAERegister("AE_EDIT_EXPLINE1");
                //nMid = GetAERegister("AE_EDIT_EXPLINE2");
                //nLow = GetAERegister("AE_EDIT_EXPLINE3");

                var ae_edit_expline = (nBHigh << 24) | (nHigh << 16) | (nMid << 8) | (nLow);
                AE_TARGET_CAL_FINAL_CAL.Text = ((ae_avrbight * factor) / ((ae_edit_gain >> 5) * (ae_edit_expline >> 4))).ToString("X2");

                isRead = false;
            }
            catch (Exception)
            {

            }
            finally
            {
                isRead = false;
            }


        }

        private async void simpleButton1_Click(object sender, EventArgs e)
        {
            //long m_nDayMode;
            isRead = true;
            long nMask = (await GetAERegister("Scene_Mode") & 0x3);
            if (nMask == 0)
            {
                AE_radiomode.SelectedIndex = 0;
            }
            else if (nMask == 1)
            {
                AE_radiomode.SelectedIndex = 1;
            }
            else if (nMask == 2)
            {
                AE_radiomode.SelectedIndex = 2;
            }
            //Scene_Switch_En
            if ((await GetAERegister("Scene_Switch_En") & 0x12) == 0x12)
            {
                checkedListBoxControl1.Items[0].CheckState = CheckState.Checked;
                checkedListBoxControl1.Items[1].Enabled = true;
            }
            else
            {
                checkedListBoxControl1.Items[0].CheckState = CheckState.Unchecked;
                checkedListBoxControl1.Items[1].Enabled = false;
                AE_radiomode.Enabled = false;
            }
            //Debug_En
            if ((await GetAERegister("Debug_En") & 0x02) == 0x00)
            {
                checkedListBoxControl1.Items[1].CheckState = CheckState.Checked;
                if (checkedListBoxControl1.Items[0].CheckState == CheckState.Checked)
                {
                    AE_radiomode.Enabled = true;
                }
            }
            else
            {
                checkedListBoxControl1.Items[1].CheckState = CheckState.Unchecked;
                AE_radiomode.Enabled = false;
            }
            isRead = false;
        }


        private void XChip_AE_Load(object sender, EventArgs e)
        {
            List<TreeListValue> GammaList = new List<TreeListValue>();
            GammaList.Add(new TreeListValue() { DisplayMember = "off", ValueMember = "0" });
            GammaList.Add(new TreeListValue() { DisplayMember = "cal_BV", ValueMember = "1" });
            GammaList.Add(new TreeListValue() { DisplayMember = "exp", ValueMember = "2" });
            COMBO_GAMMAPRE.Properties.ValueMember = "ValueMember";
            COMBO_GAMMAPRE.Properties.DisplayMember = "DisplayMember";
            COMBO_GAMMAPRE.Properties.DataSource = GammaList;
            COMBO_GAMMAPRE.ItemIndex = -1;
            Task.Run(() =>
            {

                this.Invoke((EventHandler)delegate
                {

                    //五列
                    int totalloc = 8;
                    //宽高
                    int txtW = 40;
                    int txtH = 40;
                    //生成个数64
                    for (int i = 0; i < 64; i++)
                    {
                        int row = i / totalloc;//行号
                                               //1/3=0,2/3=0,3/3=1;
                        int loc = i % totalloc;//列号

                        int txtViewY = row * txtH + 16;
                        int txtViewX = txtW * loc + 36;
                        DevExpress.XtraEditors.LabelControl labelTxt = new LabelControl();
                        labelTxt.Appearance.Font = new System.Drawing.Font("Tahoma", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
                        labelTxt.Appearance.ForeColor = System.Drawing.Color.White;
                        labelTxt.Appearance.Options.UseFont = true;
                        labelTxt.Appearance.Options.UseForeColor = true;
                        labelTxt.AutoSizeMode = DevExpress.XtraEditors.LabelAutoSizeMode.None;
                        labelTxt.Location = new System.Drawing.Point(txtViewX, txtViewY);
                        labelTxt.Name = $"labTxtJiu_{i}";
                        labelTxt.Padding = new System.Windows.Forms.Padding(10);
                        labelTxt.Size = new System.Drawing.Size(40, 40);
                        labelTxt.TabIndex = 0;
                        labelTxt.Tag = i;
                        labelTxt.Text = i.ToString("00");
                        labelTxt.Paint += new System.Windows.Forms.PaintEventHandler(this.labelControl25_Paint);
                        //this.panelControl5.Controls.Add(labelTxt);



                    }
                    for (int i = 0; i < 64; i++)
                    {
                        foreach (Control item in panelControl5.Controls)
                        {
                            if ($"AE_WEIGHT_{(i + 1).ToString("D2")}" == item.Name)
                            {
                                item.Invoke((EventHandler)delegate { item.Enabled = false; });
                            }
                        }
                    }

                    for (int i = 0; i < XChipAe.Count; i++)
                    {

                        var type = AppHelper.NameTypeToString(XChipAe[i].NameType);
                        //try
                        //{
                        //加上单选框的_en
                        if (XChipAe[i].ControlType == "1")
                        {
                            type = XChipAe[i].NameType;
                        }
                        var col = this.Controls.Find(type, true);


                        foreach (var item in col)
                        {
                            if (item is TextEdit)
                            {
                                //声明一个SuerToolTip
                                DevExpress.Utils.SuperToolTip graduationBatchSuperToolTip = new DevExpress.Utils.SuperToolTip();
                                //声明一个ToolTipTitleItem,保存标题
                                DevExpress.Utils.ToolTipTitleItem toolTipTitleItem = new DevExpress.Utils.ToolTipTitleItem();
                                String tooltips = "";

                                if (!string.IsNullOrEmpty(XChipAe[i].Bit_Wide))
                                {
                                    tooltips += $"位宽={XChipAe[i].Bit_Wide}";
                                }
                                if (!string.IsNullOrEmpty(XChipAe[i].Bit_Accuracy))
                                {
                                    tooltips += $"|精度={XChipAe[i].Bit_Accuracy}";
                                }
                                //设置标题文字
                                toolTipTitleItem.Text = tooltips;
                                //把标题添加到SuerToolTip
                                graduationBatchSuperToolTip.Items.Add(toolTipTitleItem);
                                //指定控件的SuperTip

                                ((TextEdit)item).SuperTip = graduationBatchSuperToolTip;
                                //正则判断
                                ((TextEdit)item).Properties.Mask.MaskType = DevExpress.XtraEditors.Mask.MaskType.RegEx;
                                ((TextEdit)item).Properties.Mask.EditMask = BitsHelp.GetBitsToMask(XChipAe[i].Bits, XChipAe[i].Bit_Wide, XChipAe.Where(c => c.NameType.ToLower().Contains(type) && c.ControlType == "0").Select(c => c.Bits).ToList());

                            }
                        }


                        //}
                        //catch (Exception)
                        //{
                        //    continue;
                        //}
                    }
                });


            });

        }

        private void labelControl25_Paint(object sender, PaintEventArgs e)
        {
            var txtTemp = sender as DevExpress.XtraEditors.LabelControl;
            Pen pen = new Pen(Color.DarkRed, 2);
            pen.DashStyle = DashStyle.Dash;
            e.Graphics.DrawRectangle(pen, txtTemp.DisplayRectangle);
        }


        /// <summary>
        /// 根据tag 设置文本框的的文本
        /// </summary>
        /// <param name="temp"></param>
        /// <param name="txt"></param>
        void setLabTxtJiu(object temp, string txt)
        {
            //foreach (Control item in panelControl5.Controls)
            //{
            //    if (item.Name == $"labTxtJiu_{temp}")
            //    {
            //        item.Text = txt.PadLeft(2, '0');
            //    }
            //}
        }
        void SetAE_WEIGHT(object temp, string txt)
        {
            foreach (Control item in panelControl5.Controls)
            {
                if ($"AE_WEIGHT_{(int.Parse(temp.ToString()) + 1).ToString("D2")}" == item.Name)
                {
                    var nValue = Convert.ToInt32(txt, 16) & 0x7f;
                    item.Text = nValue.ToString("X");
                }
            }
        }


        string GetCheckListBox(DevExpress.XtraEditors.CheckedListBoxControl sender)
        {
            string checkTxt = string.Empty;

            int count = sender.CheckedIndices.Count;//获得勾选的所有条集合
            var chkIndexCollection = sender.CheckedIndices;//获得所有选中行的集合

            for (int i = 0; i < count; i++)
            {
                checkTxt += chkIndexCollection[i].ToString();
            }
            return checkTxt;
        }


        #region 设置单选框


        private void checkedListBoxControl2_ItemChecking(object sender, DevExpress.XtraEditors.Controls.ItemCheckingEventArgs e)
        {

            var checkBox = sender as DevExpress.XtraEditors.CheckedListBoxControl;
            if (checkBox.CheckedItems.Count > 0)
            {
                for (int i = 0; i < checkBox.Items.Count; i++)
                {
                    if (i != e.Index)
                    {
                        checkBox.SetItemChecked(i, false);
                    }
                }
            }
        }
        #endregion       
        #region 勾选框changed
        //Scence Switch & Debug_En
        private async  void checkedListBoxControl1_ItemCheck(object sender, DevExpress.XtraEditors.Controls.ItemCheckEventArgs e)
        {
            if (isRead) return;
            //Scence Switch En 
            var nTemp1 =await GetAERegister("Scene_Switch_En");
            // Debug en
            var nTemp2 =await GetAERegister("Debug_En");
            if (checkedListBoxControl1.Items[0].CheckState == CheckState.Checked)//S勾选
            {
                await SetAeRegister("Scene_Switch_En", 0x12);
                checkedListBoxControl1.Items[1].Enabled = true;
                if (checkedListBoxControl1.Items[1].CheckState == CheckState.Checked)//D勾选
                {
                    AE_radiomode.Enabled = true;
                }
            }
            else  //S不勾选
            {
                await SetAeRegister("Scene_Switch_En", 0x00);
                checkedListBoxControl1.Items[1].Enabled = false;
                AE_radiomode.Enabled = false;
            }


            if (checkedListBoxControl1.Items[1].CheckState == CheckState.Checked)//D勾选
            {
                await SetAeRegister("Debug_En", (ulong)(nTemp2 & 0xfd));
                if (checkedListBoxControl1.Items[0].CheckState == CheckState.Checked)//S勾选
                {
                    AE_radiomode.Enabled = true;
                }
            }
            else//D不勾选
            {
                await SetAeRegister("Debug_En", (ulong)(nTemp2 | 0x02));
                AE_radiomode.Enabled = false;
            }
        }
        //Scence Mode
        private async void AE_radiomode_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (isRead) return;
            var aeradio = sender as DevExpress.XtraEditors.RadioGroup;
            if (aeradio.EditValue.ToString() == "1")
            {
               await  SetAeRegister("Scene_Mode", 0x00);
            }
            else if (aeradio.EditValue.ToString() == "2")
            {
                await SetAeRegister("Scene_Mode", 0x01);
            }
            else if (aeradio.EditValue.ToString() == "3")
            {
                await SetAeRegister("Scene_Mode", 0x02);
            }
            simpleButton5_Click(null, null);

        }
        //TARGET_SWITCH_MODE_EN
        private async void TARGET_SWITCH_MODE_EN_CheckedChanged(object sender, EventArgs e)
        {
            if (isRead) return;
            var nTemp =await GetAERegister("Target_switch_en");
            if (Target_switch_en.CheckState == CheckState.Checked)
            {
                await SetAeRegister("Target_switch_en", (ulong)(nTemp | 0x01));
                TargetSwitchEnShowHide(true);
            }
            else
            {
                await SetAeRegister("Target_switch_en", (ulong)(nTemp & 0xfe));
                TargetSwitchEnShowHide(false);
            }
        }
        //AE_ISP_GAINENABLE_EN
        private async void AE_ISP_GAINENABLE_EN_CheckedChanged(object sender, EventArgs e)
        {
            if (isRead) return;
            var nTemp =await GetAERegister("Isp_Gain_en");
            if (Isp_Gain_en.CheckState == CheckState.Checked)
            {
                await SetAeRegister("Isp_Gain_en", (ulong)(nTemp | 0x20));
            }
            else
            {
                await SetAeRegister("Isp_Gain_en", (ulong)(nTemp & 0xdf));
            }
        }
        //Flicker
        private async void checkedListBoxControl2_ItemCheck(object sender, DevExpress.XtraEditors.Controls.ItemCheckEventArgs e)
        {
            if (isRead) return;
            if (checkedListBoxControl2.Items[0].CheckState == CheckState.Checked)//50hz
            {
                await SetAeRegister("Flicker5060SW", (ulong)0x02);
            }
            if (checkedListBoxControl2.Items[1].CheckState == CheckState.Checked)//60hz
            {
                await SetAeRegister("Flicker5060SW", (ulong)0x01);
            }
            if ((checkedListBoxControl2.Items[1].CheckState == CheckState.Unchecked) && (checkedListBoxControl2.Items[0].CheckState == CheckState.Unchecked))//均不勾选
            {
                await SetAeRegister("Flicker5060SW", (ulong)0x00);
            }
            EnShowHide();
        }
        #endregion

        /// <summary>
        /// 权重
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void AE_WEIGHT_EN_CheckedChanged(object sender, EventArgs e)
        {
            if (AE_WEIGHT_EN.Checked)
            {

                for (int i = 0; i < 64; i++)
                {
                    foreach (Control item in panelControl5.Controls)
                    {
                        if ($"AE_WEIGHT_{(i + 1).ToString("D2")}" == item.Name)
                        {
                            item.Enabled = true;
                        }
                    }
                }
            }
            else
            {
                for (int i = 0; i < 64; i++)
                {
                    foreach (Control item in panelControl5.Controls)
                    {
                        if ($"AE_WEIGHT_{(i + 1).ToString("D2")}" == item.Name)
                        {
                            item.Enabled = false;
                        }
                    }
                }
            }
        }
        /// <summary>
        /// 关注使能区
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void AE_WEIGHTENABLE_EN_CheckedChanged(object sender, EventArgs e)
        {
            if (AE_WEIGHTENABLE_EN.Checked)
            {
                //Newmode_en.CheckState = CheckState.Unchecked;
                for (int i = 0; i < 64; i++)
                {
                    foreach (Control item in panelControl5.Controls)
                    {
                        if ($"AE_WT_{i}_EN" == item.Name)
                        {
                            item.Enabled = true;
                        }
                    }
                }
            }
            else
            {
                //Newmode_en.CheckState = CheckState.Checked;
                //SerialSend.WriteRegister(, 0x0, sPortTemp);
                for (int i = 0; i < 64; i++)
                {
                    foreach (Control item in panelControl5.Controls)
                    {
                        if ($"AE_WT_{i}_EN" == item.Name)
                        {
                            item.Enabled = false;
                        }
                    }
                }
            }
            if (isRead) return;
            if (XChipAe.Exists(c => c.NameType.ToLower() == ("Magnitude_en").ToLower()))
            {
                var model = XChipAe.Find(c => c.NameType.ToLower() == ("Magnitude_en").ToLower());
                var Add =await ReadRegisterAsync(model.Address);
                var Val = BitsHelp.SetBitsCheckedToUint(model.Bits, model.Hex, Add.ToString("X2"), AE_WEIGHTENABLE_EN.Checked);
                 SetAeRegister(model, Val);
            }

        }
        /// <summary>
        /// area 下发
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void AE_FOLLOW_AREA_EditValueChanged(object sender, EventArgs e)
        {
            if (isRead) return;
            var m_nFllowArea = Convert.ToInt32(AE_FOLLOW_AREA.Text, 16);
            await SetAeRegister("AE_FOLLOW_AREA_l", (ulong)(m_nFllowArea & 0xff));
            await SetAeRegister("AE_FOLLOW_AREA_m1", (ulong)((m_nFllowArea >> 8) & 0xff));
            await SetAeRegister("AE_FOLLOW_AREA_m0", (ulong)((m_nFllowArea >> 16) & 0xff));
            await SetAeRegister("AE_FOLLOW_AREA_h", (ulong)((m_nFllowArea >> 24) & 0xff));
        }
        /// <summary>
        /// 刷新
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void simpleButton4_Click(object sender, EventArgs e)
        {
          await  SetAeRegister("Refresh", 0x01);
        }

        private async void AE_WT_EN1_CheckedChanged(object sender, EventArgs e)
        {
            if (isRead) return;
            var TempCheck = sender as DevExpress.XtraEditors.CheckEdit;

            int index = int.Parse(TempCheck.Name.Replace("AE_WT_", "").Replace("_EN", ""));
            if (XChipAe.Exists(c => c.NameType.ToLower() == ("nAttentionCfg" + index.ToString()).ToLower()))
            {
                var model = XChipAe.Find(c => c.NameType.ToLower() == ("nAttentionCfg" + index.ToString()).ToLower());
                var Add = await ReadRegisterAsync(model.Address);
                var Val = BitsHelp.SetBitsCheckedToUint(model.Bits, model.Hex, Add.ToString("X2"), TempCheck.Checked);
                await SetAeRegister(model, Val);
            }

            // 按顺序异步读取寄存器
            m_nFollowArea[0] = await ReadRegisterAsync("200000B8");
            m_nFollowArea[1] = await ReadRegisterAsync("200000B9");
            m_nFollowArea[2] = await ReadRegisterAsync("200000BA");
            m_nFollowArea[3] = await ReadRegisterAsync("200000BB");
            m_nFollowArea[4] = await ReadRegisterAsync("200000BC");
            m_nFollowArea[5] = await ReadRegisterAsync("200000BD");
            m_nFollowArea[6] = await ReadRegisterAsync("200000BE");
            m_nFollowArea[7] = await ReadRegisterAsync("200000BF");

            AE_FOLLOW_AREA.Text = (m_nFollowArea[7] << 56 | m_nFollowArea[6] << 48 | m_nFollowArea[5] << 40 | m_nFollowArea[4] << 32 | m_nFollowArea[3] << 24 | m_nFollowArea[2] << 16 | m_nFollowArea[1] << 8 | m_nFollowArea[0]).ToString("X15");
        }
        private async Task<long> GetAERegister(string nameType)
        {
            
            if (XChipAe.Exists(c => c.NameType.ToLower() == nameType.ToLower()))
            {
                long var = await ReadRegisterAsync(XChipAe.Where(c => c.NameType.ToLower() == nameType.ToLower()).First().Address);
                return var;
            }
            else
            {
                DevExpress.XtraEditors.XtraMessageBox.Show($"未找到{nameType}"); return -1;
            }
        }
    
    private async Task SetAeRegister(string nameType, ulong add)
    {
        if (isRead) return;

        var model = XChipAe.Find(c => c.NameType.ToLower() == (nameType).ToLower());
        bool success = await WriteRegisterAsync(model.Address, add.ToString("X"));

        if (!success)
        {
            Console.WriteLine($"[ADBForm] SetCfaRegister 写入失败 - 地址: {model.Address}, 值: {add:X}");
        }


    }
    private async Task SetAeRegister(addressregister model, ulong add, bool isCheck = true)
        {
            if (isRead) return;
            bool success = await WriteRegisterAsync(model.Address, add.ToString("X"));

            if (!success)
            {
                Console.WriteLine($"[ADBForm] SetAfRegister 写入失败 - 地址: {model.Address}, 值: {add:X}");
            }




        }
        private void panelControl6_Paint(object sender, PaintEventArgs e)
        {

        }

        private void AE_WIN_WIDTH_X_Leave(object sender, EventArgs e)
        {
            var txtEdit = sender as DevExpress.XtraEditors.TextEdit;
            if (isRead) return;
            ///三个文本框未空就不下发
            if (string.IsNullOrEmpty(AE_WIDTH.Text) || string.IsNullOrEmpty(AE_WIN_WIDTH_X.Text) || string.IsNullOrEmpty(AE_WIN_WIDTH.Text)) return;

            //获取文本框的值
            long nWidth, nStartX, nAeWidth;
            nWidth = long.Parse(AE_WIDTH.Text);
            nStartX = long.Parse(AE_WIN_WIDTH_X.Text);
            nAeWidth = long.Parse(AE_WIN_WIDTH.Text);
            if (nStartX <= nWidth && nAeWidth <= nWidth && (nAeWidth + nStartX) <= nWidth)
            {
                //判断//var nV = AE_radiomode.Properties.Items[AE_radiomode.SelectedIndex].Value;
                if (txtEdit.Tag.ToString() == "0")// nStartX写入
                {
                    switch (AE_radiomode.SelectedIndex)
                    {
                        case 0:
                            {
                                //备注  数据库里面没有  暂时放地址 // -by syd 20201014 数据库已增加，读数据还未替换成数据库中的东西
                                //SetAeRegister("AE_WIN_WIDTH_X_0_Day", (ulong)((nStartX >> 8) & 0xff));
                                //SetAeRegister("AE_WIN_WIDTH_X_1_Day", (ulong)(nStartX & 0xff));
                                //SetAeRegister("AE_WIN_WIDTH_X_0", (ulong)((nStartX >> 8) & 0xff));
                                //SetAeRegister("AE_WIN_WIDTH_X_1", (ulong)(nStartX & 0xff));
                                if (isWrite) return;
                                if ((null != sPortTemp && sPortTemp.IsOpen) || IsUsbOpen || m_open)
                                {
                                    if (isRead) return;
                                    var txt = sender as DevExpress.XtraEditors.TextEdit;
                                    if (string.IsNullOrEmpty(txt.Text)) return;
                                    if (XChipAe.Exists(c => c.NameType.ToLower() == (txt.Name + "_h" + "_Day").ToLower()))
                                    {
                                        var model = XChipAe.Find(c => c.NameType.ToLower() == (txt.Name + "_h" + "_Day").ToLower());
                                        var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, Convert.ToString(int.Parse(txt.Text), 16));
                                        SetAeRegister(model, Val);
                                    }
                                    if (XChipAe.Exists(c => c.NameType.ToLower() == (txt.Name + "_l" + "_Day").ToLower()))
                                    {
                                        var model = XChipAe.Find(c => c.NameType.ToLower() == (txt.Name + "_l" + "_Day").ToLower());
                                        var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, Convert.ToString(int.Parse(txt.Text), 16));
                                        SetAeRegister(model, Val);
                                    }
                                    if (XChipAe.Exists(c => c.NameType.ToLower() == txt.Name.ToLower() + "_h"))
                                    {
                                        var model = XChipAe.Find(c => c.NameType.ToLower() == (txt.Name + "_h").ToLower());
                                        var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, Convert.ToString(int.Parse(txt.Text), 16));
                                        SetAeRegister(model, Val);
                                    }
                                    if (XChipAe.Exists(c => c.NameType.ToLower() == txt.Name.ToLower() + "_l"))
                                    {
                                        var model = XChipAe.Find(c => c.NameType.ToLower() == (txt.Name + "_l").ToLower());
                                        var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, Convert.ToString(int.Parse(txt.Text), 16));
                                        SetAeRegister(model, Val);
                                    }
                                }

                            }
                            break;
                        case 1:
                            {
                                //SetAeRegister("AE_WIN_WIDTH_X_0_Night", (ulong)((nStartX >> 8) & 0xff));
                                //SetAeRegister("AE_WIN_WIDTH_X_1_Night", (ulong)(nStartX & 0xff));
                                //SetAeRegister("AE_WIN_WIDTH_X_0", (ulong)((nStartX >> 8) & 0xff));
                                //SetAeRegister("AE_WIN_WIDTH_X_1", (ulong)(nStartX & 0xff));
                                if (isWrite) return;
                                if ((null != sPortTemp && sPortTemp.IsOpen) || IsUsbOpen || m_open)
                                {
                                    if (isRead) return;
                                    var txt = sender as DevExpress.XtraEditors.TextEdit;
                                    if (string.IsNullOrEmpty(txt.Text)) return;
                                    if (XChipAe.Exists(c => c.NameType.ToLower() == (txt.Name + "_h" + "_Night").ToLower()))
                                    {
                                        var model = XChipAe.Find(c => c.NameType.ToLower() == (txt.Name + "_h" + "_Night").ToLower());
                                        var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, Convert.ToString(int.Parse(txt.Text), 16));
                                        SetAeRegister(model, Val);
                                    }
                                    if (XChipAe.Exists(c => c.NameType.ToLower() == (txt.Name + "_l" + "_Night").ToLower()))
                                    {
                                        var model = XChipAe.Find(c => c.NameType.ToLower() == (txt.Name + "_l" + "_Night").ToLower());
                                        var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, Convert.ToString(int.Parse(txt.Text), 16));
                                        SetAeRegister(model, Val);
                                    }
                                    if (XChipAe.Exists(c => c.NameType.ToLower() == txt.Name.ToLower() + "_h"))
                                    {
                                        var model = XChipAe.Find(c => c.NameType.ToLower() == (txt.Name + "_h").ToLower());
                                        var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, Convert.ToString(int.Parse(txt.Text), 16));
                                        SetAeRegister(model, Val);
                                    }
                                    if (XChipAe.Exists(c => c.NameType.ToLower() == txt.Name.ToLower() + "_l"))
                                    {
                                        var model = XChipAe.Find(c => c.NameType.ToLower() == (txt.Name + "_l").ToLower());
                                        var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, Convert.ToString(int.Parse(txt.Text), 16));
                                        SetAeRegister(model, Val);
                                    }
                                }
                            }
                            break;
                        case 2:
                            {
                                //SetAeRegister("AE_WIN_WIDTH_X_0_Midnight", (ulong)((nStartX >> 8) & 0xff));
                                //SetAeRegister("AE_WIN_WIDTH_X_1_Midnight", (ulong)(nStartX & 0xff));
                                //SetAeRegister("AE_WIN_WIDTH_X_0", (ulong)((nStartX >> 8) & 0xff));
                                //SetAeRegister("AE_WIN_WIDTH_X_1", (ulong)(nStartX & 0xff));
                                if (isWrite) return;
                                if ((null != sPortTemp && sPortTemp.IsOpen) || IsUsbOpen || m_open)
                                {
                                    if (isRead) return;
                                    var txt = sender as DevExpress.XtraEditors.TextEdit;
                                    if (string.IsNullOrEmpty(txt.Text)) return;
                                    if (XChipAe.Exists(c => c.NameType.ToLower() == (txt.Name + "_h" + "_Midnight").ToLower()))
                                    {
                                        var model = XChipAe.Find(c => c.NameType.ToLower() == (txt.Name + "_h" + "_Midnight").ToLower());
                                        var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, Convert.ToString(int.Parse(txt.Text), 16));
                                        SetAeRegister(model, Val);
                                    }
                                    if (XChipAe.Exists(c => c.NameType.ToLower() == (txt.Name + "_l" + "_Midnight").ToLower()))
                                    {
                                        var model = XChipAe.Find(c => c.NameType.ToLower() == (txt.Name + "_l" + "_Midnight").ToLower());
                                        var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, Convert.ToString(int.Parse(txt.Text), 16));
                                        SetAeRegister(model, Val);
                                    }
                                    if (XChipAe.Exists(c => c.NameType.ToLower() == txt.Name.ToLower() + "_h"))
                                    {
                                        var model = XChipAe.Find(c => c.NameType.ToLower() == (txt.Name + "_h").ToLower());
                                        var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, Convert.ToString(int.Parse(txt.Text), 16));
                                        SetAeRegister(model, Val);
                                    }
                                    if (XChipAe.Exists(c => c.NameType.ToLower() == txt.Name.ToLower() + "_l"))
                                    {
                                        var model = XChipAe.Find(c => c.NameType.ToLower() == (txt.Name + "_l").ToLower());
                                        var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, Convert.ToString(int.Parse(txt.Text), 16));
                                        SetAeRegister(model, Val);
                                    }
                                }
                            }
                            break;
                        default:
                            {
                                //SetAeRegister("AE_WIN_WIDTH_X_0", (ulong)((nStartX >> 8) & 0xff));
                                //SetAeRegister("AE_WIN_WIDTH_X_1", (ulong)(nStartX & 0xff));
                                if (isWrite) return;
                                if ((null != sPortTemp && sPortTemp.IsOpen) || IsUsbOpen || m_open)
                                {
                                    if (isRead) return;
                                    var txt = sender as DevExpress.XtraEditors.TextEdit;
                                    if (string.IsNullOrEmpty(txt.Text)) return;
                                    if (XChipAe.Exists(c => c.NameType.ToLower() == txt.Name.ToLower() + "_h"))
                                    {
                                        var model = XChipAe.Find(c => c.NameType.ToLower() == (txt.Name + "_h").ToLower());
                                        var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, Convert.ToString(int.Parse(txt.Text), 16));
                                        SetAeRegister(model, Val);
                                    }
                                    if (XChipAe.Exists(c => c.NameType.ToLower() == txt.Name.ToLower() + "_l"))
                                    {
                                        var model = XChipAe.Find(c => c.NameType.ToLower() == (txt.Name + "_l").ToLower());
                                        var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, Convert.ToString(int.Parse(txt.Text), 16));
                                        SetAeRegister(model, Val);
                                    }
                                }
                            }
                            break;
                    }
                }
                else if (txtEdit.Tag.ToString() == "1")//nAeWidth写入
                {
                    switch (AE_radiomode.SelectedIndex)
                    {
                        //case 0:
                        //    {
                        //        //备注  数据库里面没有  暂时放地址
                        //        SetAeRegister("AE_WIN_WIDTH_0_Day", (ulong)((nAeWidth >> 8) & 0xff));
                        //        SetAeRegister("AE_WIN_WIDTH_1_Day", (ulong)(nAeWidth & 0xff));
                        //        SetAeRegister("AE_WIN_WIDTH_0", (ulong)((nAeWidth >> 8) & 0xff));
                        //        SetAeRegister("AE_WIN_WIDTH_1", (ulong)(nAeWidth & 0xff));
                        //    }
                        //    break;
                        //case 1:
                        //    {
                        //        SetAeRegister("AE_WIN_WIDTH_0_Night", (ulong)((nAeWidth >> 8) & 0xff));
                        //        SetAeRegister("AE_WIN_WIDTH_1_Night", (ulong)(nAeWidth & 0xff));
                        //        SetAeRegister("AE_WIN_WIDTH_0", (ulong)((nAeWidth >> 8) & 0xff));
                        //        SetAeRegister("AE_WIN_WIDTH_1", (ulong)(nAeWidth & 0xff));
                        //    }
                        //    break;
                        //case 2:
                        //    {
                        //        SetAeRegister("AE_WIN_WIDTH_0_Midnight", (ulong)((nAeWidth >> 8) & 0xff));
                        //        SetAeRegister("AE_WIN_WIDTH_1_Midnight", (ulong)(nAeWidth & 0xff));
                        //        SetAeRegister("AE_WIN_WIDTH_0", (ulong)((nAeWidth >> 8) & 0xff));
                        //        SetAeRegister("AE_WIN_WIDTH_1", (ulong)(nAeWidth & 0xff));
                        //    }
                        //    break;
                        //default:
                        //    {
                        //        SetAeRegister("AE_WIN_WIDTH_0", (ulong)((nAeWidth >> 8) & 0xff));
                        //        SetAeRegister("AE_WIN_WIDTH_1", (ulong)(nAeWidth & 0xff));
                        //    }
                        //    break;
                        case 0:
                            {

                                if (isWrite) return;
                                if ((null != sPortTemp && sPortTemp.IsOpen) || IsUsbOpen || m_open)
                                {
                                    if (isRead) return;
                                    var txt = sender as DevExpress.XtraEditors.TextEdit;
                                    if (string.IsNullOrEmpty(txt.Text)) return;
                                    if (XChipAe.Exists(c => c.NameType.ToLower() == (txt.Name + "_h" + "_Day").ToLower()))
                                    {
                                        var model = XChipAe.Find(c => c.NameType.ToLower() == (txt.Name + "_h" + "_Day").ToLower());
                                        var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, Convert.ToString(int.Parse(txt.Text), 16));
                                        SetAeRegister(model, Val);
                                    }
                                    if (XChipAe.Exists(c => c.NameType.ToLower() == (txt.Name + "_l" + "_Day").ToLower()))
                                    {
                                        var model = XChipAe.Find(c => c.NameType.ToLower() == (txt.Name + "_l" + "_Day").ToLower());
                                        var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, Convert.ToString(int.Parse(txt.Text), 16));
                                        SetAeRegister(model, Val);
                                    }
                                    if (XChipAe.Exists(c => c.NameType.ToLower() == txt.Name.ToLower() + "_h"))
                                    {
                                        var model = XChipAe.Find(c => c.NameType.ToLower() == (txt.Name + "_h").ToLower());
                                        var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, Convert.ToString(int.Parse(txt.Text), 16));
                                        SetAeRegister(model, Val);
                                    }
                                    if (XChipAe.Exists(c => c.NameType.ToLower() == txt.Name.ToLower() + "_l"))
                                    {
                                        var model = XChipAe.Find(c => c.NameType.ToLower() == (txt.Name + "_l").ToLower());
                                        var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, Convert.ToString(int.Parse(txt.Text), 16));
                                        SetAeRegister(model, Val);
                                    }
                                }

                            }
                            break;
                        case 1:
                            {

                                if (isWrite) return;
                                if ((null != sPortTemp && sPortTemp.IsOpen) || IsUsbOpen || m_open)
                                {
                                    if (isRead) return;
                                    var txt = sender as DevExpress.XtraEditors.TextEdit;
                                    if (string.IsNullOrEmpty(txt.Text)) return;
                                    if (XChipAe.Exists(c => c.NameType.ToLower() == (txt.Name + "_h" + "_Night").ToLower()))
                                    {
                                        var model = XChipAe.Find(c => c.NameType.ToLower() == (txt.Name + "_h" + "_Night").ToLower());
                                        var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, Convert.ToString(int.Parse(txt.Text), 16));
                                        SetAeRegister(model, Val);
                                    }
                                    if (XChipAe.Exists(c => c.NameType.ToLower() == (txt.Name + "_l" + "_Night").ToLower()))
                                    {
                                        var model = XChipAe.Find(c => c.NameType.ToLower() == (txt.Name + "_l" + "_Night").ToLower());
                                        var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, Convert.ToString(int.Parse(txt.Text), 16));
                                        SetAeRegister(model, Val);
                                    }
                                    if (XChipAe.Exists(c => c.NameType.ToLower() == txt.Name.ToLower() + "_h"))
                                    {
                                        var model = XChipAe.Find(c => c.NameType.ToLower() == (txt.Name + "_h").ToLower());
                                        var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, Convert.ToString(int.Parse(txt.Text), 16));
                                        SetAeRegister(model, Val);
                                    }
                                    if (XChipAe.Exists(c => c.NameType.ToLower() == txt.Name.ToLower() + "_l"))
                                    {
                                        var model = XChipAe.Find(c => c.NameType.ToLower() == (txt.Name + "_l").ToLower());
                                        var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, Convert.ToString(int.Parse(txt.Text), 16));
                                        SetAeRegister(model, Val);
                                    }
                                }
                            }
                            break;
                        case 2:
                            {

                                if (isWrite) return;
                                if ((null != sPortTemp && sPortTemp.IsOpen) || IsUsbOpen || m_open)
                                {
                                    if (isRead) return;
                                    var txt = sender as DevExpress.XtraEditors.TextEdit;
                                    if (string.IsNullOrEmpty(txt.Text)) return;
                                    if (XChipAe.Exists(c => c.NameType.ToLower() == (txt.Name + "_h" + "_Midnight").ToLower()))
                                    {
                                        var model = XChipAe.Find(c => c.NameType.ToLower() == (txt.Name + "_h" + "_Midnight").ToLower());
                                        var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, Convert.ToString(int.Parse(txt.Text), 16));
                                        SetAeRegister(model, Val);
                                    }
                                    if (XChipAe.Exists(c => c.NameType.ToLower() == (txt.Name + "_l" + "_Midnight").ToLower()))
                                    {
                                        var model = XChipAe.Find(c => c.NameType.ToLower() == (txt.Name + "_l" + "_Midnight").ToLower());
                                        var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, Convert.ToString(int.Parse(txt.Text), 16));
                                        SetAeRegister(model, Val);
                                    }
                                    if (XChipAe.Exists(c => c.NameType.ToLower() == txt.Name.ToLower() + "_h"))
                                    {
                                        var model = XChipAe.Find(c => c.NameType.ToLower() == (txt.Name + "_h").ToLower());
                                        var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, Convert.ToString(int.Parse(txt.Text), 16));
                                        SetAeRegister(model, Val);
                                    }
                                    if (XChipAe.Exists(c => c.NameType.ToLower() == txt.Name.ToLower() + "_l"))
                                    {
                                        var model = XChipAe.Find(c => c.NameType.ToLower() == (txt.Name + "_l").ToLower());
                                        var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, Convert.ToString(int.Parse(txt.Text), 16));
                                        SetAeRegister(model, Val);
                                    }
                                }
                            }
                            break;
                        default:
                            {

                                if (isWrite) return;
                                if ((null != sPortTemp && sPortTemp.IsOpen) || IsUsbOpen || m_open)
                                {
                                    if (isRead) return;
                                    var txt = sender as DevExpress.XtraEditors.TextEdit;
                                    if (string.IsNullOrEmpty(txt.Text)) return;
                                    if (XChipAe.Exists(c => c.NameType.ToLower() == txt.Name.ToLower() + "_h"))
                                    {
                                        var model = XChipAe.Find(c => c.NameType.ToLower() == (txt.Name + "_h").ToLower());
                                        var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, Convert.ToString(int.Parse(txt.Text), 16));
                                        SetAeRegister(model, Val);
                                    }
                                    if (XChipAe.Exists(c => c.NameType.ToLower() == txt.Name.ToLower() + "_l"))
                                    {
                                        var model = XChipAe.Find(c => c.NameType.ToLower() == (txt.Name + "_l").ToLower());
                                        var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, Convert.ToString(int.Parse(txt.Text), 16));
                                        SetAeRegister(model, Val);
                                    }
                                }
                            }
                            break;
                    }
                }

            }
            else
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("AE窗口范围超过图像大小,重新输入");
                return;
            }
        }

        private void AE_WIN_HEIGHT_Y_Leave(object sender, EventArgs e)
        {
            var txtEdit = sender as DevExpress.XtraEditors.TextEdit;
            if (isRead) return;
            if (string.IsNullOrEmpty(AE_HEIGHT.Text) || string.IsNullOrEmpty(AE_WIN_HEIGHT_Y.Text) || string.IsNullOrEmpty(AE_WIN_HEIGHT.Text)) return;
            long nHeight, nStartY, nAeHeight;
            nHeight = long.Parse(AE_HEIGHT.Text);
            nStartY = long.Parse(AE_WIN_HEIGHT_Y.Text);
            nAeHeight = long.Parse(AE_WIN_HEIGHT.Text);
            if (nStartY <= nHeight && nAeHeight <= nHeight && (nAeHeight + nStartY) <= nHeight)
            {
                if (txtEdit.Tag.ToString() == "0")// nStartY写入
                {
                    switch (AE_radiomode.SelectedIndex)
                    {
                        //case 0:
                        //    {
                        //        //备注  数据库里面没有  暂时放地址
                        //        SetAeRegister("AE_WIN_HEIGHT_Y_0_Day", (ulong)((nStartY >> 8) & 0xff));
                        //        SetAeRegister("AE_WIN_HEIGHT_Y_1_Day", (ulong)(nStartY & 0xff));
                        //        SetAeRegister("AE_WIN_HEIGHT_Y_0", (ulong)((nStartY >> 8) & 0xff));
                        //        SetAeRegister("AE_WIN_HEIGHT_Y_1", (ulong)(nStartY & 0xff));
                        //    }
                        //    break;
                        //case 1:
                        //    {
                        //        SetAeRegister("AE_WIN_HEIGHT_Y_0_Night", (ulong)((nStartY >> 8) & 0xff));
                        //        SetAeRegister("AE_WIN_HEIGHT_Y_1_Night", (ulong)(nStartY & 0xff));
                        //        SetAeRegister("AE_WIN_HEIGHT_Y_0", (ulong)((nStartY >> 8) & 0xff));
                        //        SetAeRegister("AE_WIN_HEIGHT_Y_1", (ulong)(nStartY & 0xff));
                        //    }
                        //    break;
                        //case 2:
                        //    {
                        //        SetAeRegister("AE_WIN_HEIGHT_Y_0_Midnight", (ulong)((nStartY >> 8) & 0xff));
                        //        SetAeRegister("AE_WIN_HEIGHT_Y_1_Midnight", (ulong)(nStartY & 0xff));
                        //        SetAeRegister("AE_WIN_HEIGHT_Y_0", (ulong)((nStartY >> 8) & 0xff));
                        //        SetAeRegister("AE_WIN_HEIGHT_Y_1", (ulong)(nStartY & 0xff));
                        //    }
                        //    break;
                        //default:
                        //    {
                        //        SetAeRegister("AE_WIN_HEIGHT_Y_0", (ulong)((nStartY >> 8) & 0xff));
                        //        SetAeRegister("AE_WIN_HEIGHT_Y_1", (ulong)(nStartY & 0xff));
                        //    }
                        //    break;
                        case 0:
                            {

                                if (isWrite) return;
                                if ((null != sPortTemp && sPortTemp.IsOpen) || IsUsbOpen || m_open)
                                {
                                    if (isRead) return;
                                    var txt = sender as DevExpress.XtraEditors.TextEdit;
                                    if (string.IsNullOrEmpty(txt.Text)) return;
                                    if (XChipAe.Exists(c => c.NameType.ToLower() == (txt.Name + "_h" + "_Day").ToLower()))
                                    {
                                        var model = XChipAe.Find(c => c.NameType.ToLower() == (txt.Name + "_h" + "_Day").ToLower());
                                        var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, Convert.ToString(int.Parse(txt.Text), 16));
                                        SetAeRegister(model, Val);
                                    }
                                    if (XChipAe.Exists(c => c.NameType.ToLower() == (txt.Name + "_l" + "_Day").ToLower()))
                                    {
                                        var model = XChipAe.Find(c => c.NameType.ToLower() == (txt.Name + "_l" + "_Day").ToLower());
                                        var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, Convert.ToString(int.Parse(txt.Text), 16));
                                        SetAeRegister(model, Val);
                                    }
                                    if (XChipAe.Exists(c => c.NameType.ToLower() == txt.Name.ToLower() + "_h"))
                                    {
                                        var model = XChipAe.Find(c => c.NameType.ToLower() == (txt.Name + "_h").ToLower());
                                        var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, Convert.ToString(int.Parse(txt.Text), 16));
                                        SetAeRegister(model, Val);
                                    }
                                    if (XChipAe.Exists(c => c.NameType.ToLower() == txt.Name.ToLower() + "_l"))
                                    {
                                        var model = XChipAe.Find(c => c.NameType.ToLower() == (txt.Name + "_l").ToLower());
                                        var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, Convert.ToString(int.Parse(txt.Text), 16));
                                        SetAeRegister(model, Val);
                                    }
                                }

                            }
                            break;
                        case 1:
                            {

                                if (isWrite) return;
                                if ((null != sPortTemp && sPortTemp.IsOpen) || IsUsbOpen || m_open)
                                {
                                    if (isRead) return;
                                    var txt = sender as DevExpress.XtraEditors.TextEdit;
                                    if (string.IsNullOrEmpty(txt.Text)) return;
                                    if (XChipAe.Exists(c => c.NameType.ToLower() == (txt.Name + "_h" + "_Night").ToLower()))
                                    {
                                        var model = XChipAe.Find(c => c.NameType.ToLower() == (txt.Name + "_h" + "_Night").ToLower());
                                        var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, Convert.ToString(int.Parse(txt.Text), 16));
                                        SetAeRegister(model, Val);
                                    }
                                    if (XChipAe.Exists(c => c.NameType.ToLower() == (txt.Name + "_l" + "_Night").ToLower()))
                                    {
                                        var model = XChipAe.Find(c => c.NameType.ToLower() == (txt.Name + "_l" + "_Night").ToLower());
                                        var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, Convert.ToString(int.Parse(txt.Text), 16));
                                        SetAeRegister(model, Val);
                                    }
                                    if (XChipAe.Exists(c => c.NameType.ToLower() == txt.Name.ToLower() + "_h"))
                                    {
                                        var model = XChipAe.Find(c => c.NameType.ToLower() == (txt.Name + "_h").ToLower());
                                        var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, Convert.ToString(int.Parse(txt.Text), 16));
                                        SetAeRegister(model, Val);
                                    }
                                    if (XChipAe.Exists(c => c.NameType.ToLower() == txt.Name.ToLower() + "_l"))
                                    {
                                        var model = XChipAe.Find(c => c.NameType.ToLower() == (txt.Name + "_l").ToLower());
                                        var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, Convert.ToString(int.Parse(txt.Text), 16));
                                        SetAeRegister(model, Val);
                                    }
                                }
                            }
                            break;
                        case 2:
                            {

                                if (isWrite) return;
                                if ((null != sPortTemp && sPortTemp.IsOpen) || IsUsbOpen || m_open)
                                {
                                    if (isRead) return;
                                    var txt = sender as DevExpress.XtraEditors.TextEdit;
                                    if (string.IsNullOrEmpty(txt.Text)) return;
                                    if (XChipAe.Exists(c => c.NameType.ToLower() == (txt.Name + "_h" + "_Midnight").ToLower()))
                                    {
                                        var model = XChipAe.Find(c => c.NameType.ToLower() == (txt.Name + "_h" + "_Midnight").ToLower());
                                        var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, Convert.ToString(int.Parse(txt.Text), 16));
                                        SetAeRegister(model, Val);
                                    }
                                    if (XChipAe.Exists(c => c.NameType.ToLower() == (txt.Name + "_l" + "_Midnight").ToLower()))
                                    {
                                        var model = XChipAe.Find(c => c.NameType.ToLower() == (txt.Name + "_l" + "_Midnight").ToLower());
                                        var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, Convert.ToString(int.Parse(txt.Text), 16));
                                        SetAeRegister(model, Val);
                                    }
                                    if (XChipAe.Exists(c => c.NameType.ToLower() == txt.Name.ToLower() + "_h"))
                                    {
                                        var model = XChipAe.Find(c => c.NameType.ToLower() == (txt.Name + "_h").ToLower());
                                        var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, Convert.ToString(int.Parse(txt.Text), 16));
                                        SetAeRegister(model, Val);
                                    }
                                    if (XChipAe.Exists(c => c.NameType.ToLower() == txt.Name.ToLower() + "_l"))
                                    {
                                        var model = XChipAe.Find(c => c.NameType.ToLower() == (txt.Name + "_l").ToLower());
                                        var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, Convert.ToString(int.Parse(txt.Text), 16));
                                        SetAeRegister(model, Val);
                                    }
                                }
                            }
                            break;
                        default:
                            {

                                if (isWrite) return;
                                if ((null != sPortTemp && sPortTemp.IsOpen) || IsUsbOpen || m_open)
                                {
                                    if (isRead) return;
                                    var txt = sender as DevExpress.XtraEditors.TextEdit;
                                    if (string.IsNullOrEmpty(txt.Text)) return;
                                    if (XChipAe.Exists(c => c.NameType.ToLower() == txt.Name.ToLower() + "_h"))
                                    {
                                        var model = XChipAe.Find(c => c.NameType.ToLower() == (txt.Name + "_h").ToLower());
                                        var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, Convert.ToString(int.Parse(txt.Text), 16));
                                        SetAeRegister(model, Val);
                                    }
                                    if (XChipAe.Exists(c => c.NameType.ToLower() == txt.Name.ToLower() + "_l"))
                                    {
                                        var model = XChipAe.Find(c => c.NameType.ToLower() == (txt.Name + "_l").ToLower());
                                        var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, Convert.ToString(int.Parse(txt.Text), 16));
                                        SetAeRegister(model, Val);
                                    }
                                }
                            }
                            break;
                    }
                }
                else if (txtEdit.Tag.ToString() == "1")//nAeHeight写入
                {
                    switch (AE_radiomode.SelectedIndex)
                    {
                        //case 0:
                        //    {
                        //        //备注  数据库里面没有  暂时放地址
                        //        SetAeRegister("AE_WIN_HEIGHT_0_Day", (ulong)((nAeHeight >> 8) & 0xff));
                        //        SetAeRegister("AE_WIN_HEIGHT_1_Day", (ulong)(nAeHeight & 0xff));
                        //        SetAeRegister("AE_WIN_HEIGHT_0", (ulong)((nAeHeight >> 8) & 0xff));
                        //        SetAeRegister("AE_WIN_HEIGHT_1", (ulong)(nAeHeight & 0xff));
                        //    }
                        //    break;
                        //case 1:
                        //    {
                        //        SetAeRegister("AE_WIN_HEIGHT_0_Night", (ulong)((nAeHeight >> 8) & 0xff));
                        //        SetAeRegister("AE_WIN_HEIGHT_1_Night", (ulong)(nAeHeight & 0xff));
                        //        SetAeRegister("AE_WIN_HEIGHT_0", (ulong)((nAeHeight >> 8) & 0xff));
                        //        SetAeRegister("AE_WIN_HEIGHT_1", (ulong)(nAeHeight & 0xff));
                        //    }
                        //    break;
                        //case 2:
                        //    {
                        //        SetAeRegister("AE_WIN_HEIGHT_0_Midnight", (ulong)((nAeHeight >> 8) & 0xff));
                        //        SetAeRegister("AE_WIN_HEIGHT_1_Midnight", (ulong)(nAeHeight & 0xff));
                        //        SetAeRegister("AE_WIN_HEIGHT_0", (ulong)((nAeHeight >> 8) & 0xff));
                        //        SetAeRegister("AE_WIN_HEIGHT_1", (ulong)(nAeHeight & 0xff));
                        //    }
                        //    break;
                        //default:
                        //    {
                        //        SetAeRegister("AE_WIN_HEIGHT_0", (ulong)((nAeHeight >> 8) & 0xff));
                        //        SetAeRegister("AE_WIN_HEIGHT_1", (ulong)(nAeHeight & 0xff));
                        //    }
                        //    break;
                        case 0:
                            {

                                if (isWrite) return;
                                if ((null != sPortTemp && sPortTemp.IsOpen) || IsUsbOpen || m_open)
                                {
                                    if (isRead) return;
                                    var txt = sender as DevExpress.XtraEditors.TextEdit;
                                    if (string.IsNullOrEmpty(txt.Text)) return;
                                    if (XChipAe.Exists(c => c.NameType.ToLower() == (txt.Name + "_h" + "_Day").ToLower()))
                                    {
                                        var model = XChipAe.Find(c => c.NameType.ToLower() == (txt.Name + "_h" + "_Day").ToLower());
                                        var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, Convert.ToString(int.Parse(txt.Text), 16));
                                        SetAeRegister(model, Val);
                                    }
                                    if (XChipAe.Exists(c => c.NameType.ToLower() == (txt.Name + "_l" + "_Day").ToLower()))
                                    {
                                        var model = XChipAe.Find(c => c.NameType.ToLower() == (txt.Name + "_l" + "_Day").ToLower());
                                        var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, Convert.ToString(int.Parse(txt.Text), 16));
                                        SetAeRegister(model, Val);
                                    }
                                    if (XChipAe.Exists(c => c.NameType.ToLower() == txt.Name.ToLower() + "_h"))
                                    {
                                        var model = XChipAe.Find(c => c.NameType.ToLower() == (txt.Name + "_h").ToLower());
                                        var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, Convert.ToString(int.Parse(txt.Text), 16));
                                        SetAeRegister(model, Val);
                                    }
                                    if (XChipAe.Exists(c => c.NameType.ToLower() == txt.Name.ToLower() + "_l"))
                                    {
                                        var model = XChipAe.Find(c => c.NameType.ToLower() == (txt.Name + "_l").ToLower());
                                        var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, Convert.ToString(int.Parse(txt.Text), 16));
                                        SetAeRegister(model, Val);
                                    }
                                }

                            }
                            break;
                        case 1:
                            {

                                if (isWrite) return;
                                if ((null != sPortTemp && sPortTemp.IsOpen) || IsUsbOpen || m_open)
                                {
                                    if (isRead) return;
                                    var txt = sender as DevExpress.XtraEditors.TextEdit;
                                    if (string.IsNullOrEmpty(txt.Text)) return;
                                    if (XChipAe.Exists(c => c.NameType.ToLower() == (txt.Name + "_h" + "_Night").ToLower()))
                                    {
                                        var model = XChipAe.Find(c => c.NameType.ToLower() == (txt.Name + "_h" + "_Night").ToLower());
                                        var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, Convert.ToString(int.Parse(txt.Text), 16));
                                        SetAeRegister(model, Val);
                                    }
                                    if (XChipAe.Exists(c => c.NameType.ToLower() == (txt.Name + "_l" + "_Night").ToLower()))
                                    {
                                        var model = XChipAe.Find(c => c.NameType.ToLower() == (txt.Name + "_l" + "_Night").ToLower());
                                        var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, Convert.ToString(int.Parse(txt.Text), 16));
                                        SetAeRegister(model, Val);
                                    }
                                    if (XChipAe.Exists(c => c.NameType.ToLower() == txt.Name.ToLower() + "_h"))
                                    {
                                        var model = XChipAe.Find(c => c.NameType.ToLower() == (txt.Name + "_h").ToLower());
                                        var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, Convert.ToString(int.Parse(txt.Text), 16));
                                        SetAeRegister(model, Val);
                                    }
                                    if (XChipAe.Exists(c => c.NameType.ToLower() == txt.Name.ToLower() + "_l"))
                                    {
                                        var model = XChipAe.Find(c => c.NameType.ToLower() == (txt.Name + "_l").ToLower());
                                        var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, Convert.ToString(int.Parse(txt.Text), 16));
                                        SetAeRegister(model, Val);
                                    }
                                }
                            }
                            break;
                        case 2:
                            {

                                if (isWrite) return;
                                if ((null != sPortTemp && sPortTemp.IsOpen) || IsUsbOpen || m_open)
                                {
                                    if (isRead) return;
                                    var txt = sender as DevExpress.XtraEditors.TextEdit;
                                    if (string.IsNullOrEmpty(txt.Text)) return;
                                    if (XChipAe.Exists(c => c.NameType.ToLower() == (txt.Name + "_h" + "_Midnight").ToLower()))
                                    {
                                        var model = XChipAe.Find(c => c.NameType.ToLower() == (txt.Name + "_h" + "_Midnight").ToLower());
                                        var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, Convert.ToString(int.Parse(txt.Text), 16));
                                        SetAeRegister(model, Val);
                                    }
                                    if (XChipAe.Exists(c => c.NameType.ToLower() == (txt.Name + "_l" + "_Midnight").ToLower()))
                                    {
                                        var model = XChipAe.Find(c => c.NameType.ToLower() == (txt.Name + "_l" + "_Midnight").ToLower());
                                        var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, Convert.ToString(int.Parse(txt.Text), 16));
                                        SetAeRegister(model, Val);
                                    }
                                    if (XChipAe.Exists(c => c.NameType.ToLower() == txt.Name.ToLower() + "_h"))
                                    {
                                        var model = XChipAe.Find(c => c.NameType.ToLower() == (txt.Name + "_h").ToLower());
                                        var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, Convert.ToString(int.Parse(txt.Text), 16));
                                        SetAeRegister(model, Val);
                                    }
                                    if (XChipAe.Exists(c => c.NameType.ToLower() == txt.Name.ToLower() + "_l"))
                                    {
                                        var model = XChipAe.Find(c => c.NameType.ToLower() == (txt.Name + "_l").ToLower());
                                        var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, Convert.ToString(int.Parse(txt.Text), 16));
                                        SetAeRegister(model, Val);
                                    }
                                }
                            }
                            break;
                        default:
                            {

                                if (isWrite) return;
                                if (true)
                                {
                                    if (isRead) return;
                                    var txt = sender as DevExpress.XtraEditors.TextEdit;
                                    if (string.IsNullOrEmpty(txt.Text)) return;
                                    if (XChipAe.Exists(c => c.NameType.ToLower() == txt.Name.ToLower() + "_h"))
                                    {
                                        var model = XChipAe.Find(c => c.NameType.ToLower() == (txt.Name + "_h").ToLower());
                                        var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, Convert.ToString(int.Parse(txt.Text), 16));
                                        SetAeRegister(model, Val);
                                    }
                                    if (XChipAe.Exists(c => c.NameType.ToLower() == txt.Name.ToLower() + "_l"))
                                    {
                                        var model = XChipAe.Find(c => c.NameType.ToLower() == (txt.Name + "_l").ToLower());
                                        var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, Convert.ToString(int.Parse(txt.Text), 16));
                                        SetAeRegister(model, Val);
                                    }
                                }
                            }
                            break;
                    }
                }
            }
            else
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("AE窗口范围超过图像大小,重新输入");
                return;
            }
        }

        private async void AE_WEIGHT1_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            if (isRead) return;
            var txtedit = sender as DevExpress.XtraEditors.TextEdit;
            if (string.IsNullOrEmpty(txtedit.Text)) return;
            for (int i = 0; i < 64; i++)
            {
                foreach (Control item in panelControl5.Controls)
                {
                    if ($"AE_WEIGHT_{(i + 1).ToString("D2")}" == item.Name && (txtedit.Name == item.Name))
                    {
                        var TempTxt = item.Text;
                        if (Convert.ToInt32(item.Text, 16) > 0x40)
                        {
                            TempTxt = "40";
                        }
                        switch (AE_radiomode.SelectedIndex)
                        {
                            case 0:
                                { //day mode
                                    var uValue =await GetAERegister($"AE_WEIGHT_{(i + 1).ToString("D2")}_Day");
                                    if ((uValue >> 7) == 1)
                                    {
                                        SetAeRegister($"AE_WEIGHT_{(i + 1).ToString("D2")}_Day", (Convert.ToUInt32(TempTxt, 16) | 0x80));

                                    }
                                    else
                                    {
                                        SetAeRegister($"AE_WEIGHT_{(i + 1).ToString("D2")}_Day", (Convert.ToUInt32(TempTxt, 16) & 0x7f));

                                    }
                                }
                                break;
                            case 1:
                                { //night mode
                                    var uValue =await GetAERegister($"AE_WEIGHT_{(i + 1).ToString("D2")}_Night");
                                    if ((uValue >> 7) == 1)
                                    {
                                        SetAeRegister($"AE_WEIGHT_{(i + 1).ToString("D2")}_Night", (Convert.ToUInt32(TempTxt, 16) | 0x80));

                                    }
                                    else
                                    {
                                        SetAeRegister($"AE_WEIGHT_{(i + 1).ToString("D2")}_Night", (Convert.ToUInt32(TempTxt, 16) & 0x7f));

                                    }
                                }
                                break;
                            case 2:
                                {
                                    //midnight mode
                                    var uValue =await GetAERegister($"AE_WEIGHT_{(i + 1).ToString("D2")}_Midnight");
                                    if ((uValue >> 7) == 1)
                                    {
                                        SetAeRegister($"AE_WEIGHT_{(i + 1).ToString("D2")}_Midnight", (Convert.ToUInt32(TempTxt, 16) | 0x80));

                                    }
                                    else
                                    {
                                        SetAeRegister($"AE_WEIGHT_{(i + 1).ToString("D2")}_Midnight", (Convert.ToUInt32(TempTxt, 16) & 0x7f));

                                    }
                                }
                                break;
                            default:
                                break;
                        }

                        var nTemp =await GetAERegister($"AE_WEIGHT_{(i + 1).ToString("D2")}");//SerialSend.ReadRegister((ulong)( | (0x5B + i)), sPortTemp);
                        if ((nTemp >> 7) == 1)
                        {
                            SetAeRegister($"AE_WEIGHT_{(i + 1).ToString("D2")}", (Convert.ToUInt32(TempTxt, 16) | 0x80)); //SerialSend.WriteRegister((ulong)( | (0x5B + i)), (ulong)(Convert.ToInt32(TempTxt, 16) | 0x80), sPortTemp);
                        }
                        else
                        {
                            SetAeRegister($"AE_WEIGHT_{(i + 1).ToString("D2")}", (Convert.ToUInt32(TempTxt, 16) & 0x7f));// SerialSend.WriteRegister((ulong)( | (0x5B + i)), (ulong)(Convert.ToInt32(TempTxt, 16) & 0x7f), sPortTemp);
                        }
                        //重新赋值
                        setLabTxtJiu(i, nTemp.ToString("X2"));
                        if (Convert.ToInt32(item.Text, 16) > 0x40)
                        {
                            isRead = true;
                            item.Text = "40";
                            isRead = false;
                            return;
                        }
                        //setLabTxtJiu(txtedit.Tag, txtedit.Text);
                    }
                }
            }
            //setLabTxtJiu(txtedit.Tag, txtedit.Text);
        }

        private void AE_BRIGHTNESS_Leave(object sender, EventArgs e)
        {
            //if (isWrite) return;
            //if (isRead) return;
            //var txtedit = sender as DevExpress.XtraEditors.TextEdit;
            //if (string.IsNullOrEmpty(txtedit.Text)) return;
            ////注： 这个新写的 数据库中没有
            //SetAeRegister("AE_BRIGHTNESS0", (((ulong)Convert.ToInt32(txtedit.Text, 16) >> 8) & 0xff));
            //SetAeRegister("AE_BRIGHTNESS1", ((ulong)Convert.ToInt32(txtedit.Text, 16) & 0xff));

            if (isWrite) return;

            if (isRead) return;
            var txt = sender as DevExpress.XtraEditors.TextEdit;
            if (string.IsNullOrEmpty(txt.Text)) return;
            if (XChipAe.Exists(c => c.NameType.ToLower() == txt.Name.ToLower() + "_h"))
            {
                var model = XChipAe.Find(c => c.NameType.ToLower() == (txt.Name + "_h").ToLower());
                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                SetAeRegister(model, Val);
            }
            if (XChipAe.Exists(c => c.NameType.ToLower() == txt.Name.ToLower() + "_l"))
            {
                var model = XChipAe.Find(c => c.NameType.ToLower() == (txt.Name + "_l").ToLower());
                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                SetAeRegister(model, Val);
            }

        }

        private void AE_MAXGAIN_Leave(object sender, EventArgs e)
        {
            //if (isWrite) return;
            //if (isRead) return;
            //var txtedit = sender as DevExpress.XtraEditors.TextEdit;
            //if (string.IsNullOrEmpty(txtedit.Text)) return;
            //注： 这个新写的 数据库中没有
            if (Convert.ToInt32(AE_MAXGAIN.Text, 16) >= 0xffff || Convert.ToInt32(AE_MAXGAIN.Text, 16) < 0)
            {
                if (Convert.ToInt32(AE_MAXGAIN.Text, 16) == 0xffff) return;
                AE_MAXGAIN.Text = "ffff"; return;
            }
            //SetAeRegister("AE_MAXGAIN0", (((ulong)Convert.ToInt32(txtedit.Text, 16) >> 8) & 0xff));
            //SetAeRegister("AE_MAXGAIN1", ((ulong)Convert.ToInt32(txtedit.Text, 16) & 0xff));
            if (isWrite) return;

            if (isRead) return;
            var txt = sender as DevExpress.XtraEditors.TextEdit;
            if (string.IsNullOrEmpty(txt.Text)) return;
            if (XChipAe.Exists(c => c.NameType.ToLower() == txt.Name.ToLower() + "_h"))
            {
                var model = XChipAe.Find(c => c.NameType.ToLower() == (txt.Name + "_h").ToLower());
                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                SetAeRegister(model, Val);
            }
            if (XChipAe.Exists(c => c.NameType.ToLower() == txt.Name.ToLower() + "_l"))
            {
                var model = XChipAe.Find(c => c.NameType.ToLower() == (txt.Name + "_l").ToLower());
                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                SetAeRegister(model, Val);
            }

        }

        private void AE_MINEXPOSURE_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            var txtedit = sender as DevExpress.XtraEditors.TextEdit;
            if (string.IsNullOrEmpty(txtedit.Text)) return;
            //注： 这个新写的 数据库中没有 , 
            if (Convert.ToInt32(AE_MINEXPOSURE.Text, 16) >= 0xffff || Convert.ToInt32(AE_MINEXPOSURE.Text, 16) < 0)
            {
                if (Convert.ToInt32(AE_MINEXPOSURE.Text, 16) == 0xffff) return;
                AE_MINEXPOSURE.Text = "ffff"; return;
            }
            if (Convert.ToInt32(AE_MINEXPOSURE.Text, 16) <= Convert.ToInt32(AE_MAXEXPOSURE.Text, 16))
            {
                //SetAeRegister("AE_MINEXPOSURE0", (((ulong)Convert.ToInt32(txtedit.Text, 16) >> 8) & 0xff));
                //SetAeRegister("AE_MINEXPOSURE1", ((ulong)Convert.ToInt32(txtedit.Text, 16) & 0xf0));
                if (isWrite) return;

                if (isRead) return;
                if (string.IsNullOrEmpty(txtedit.Text)) return;
                if (XChipAe.Exists(c => c.NameType.ToLower() == txtedit.Name.ToLower() + "_h"))
                {
                    var model = XChipAe.Find(c => c.NameType.ToLower() == (txtedit.Name + "_h").ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txtedit.Text);
                    SetAeRegister(model, Val);
                }
                if (XChipAe.Exists(c => c.NameType.ToLower() == txtedit.Name.ToLower() + "_l"))
                {
                    var model = XChipAe.Find(c => c.NameType.ToLower() == (txtedit.Name + "_l").ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txtedit.Text);
                    SetAeRegister(model, Val);
                }

            }
            else
            {
                //SetAeRegister("AE_MINEXPOSURE0", (((ulong)Convert.ToInt32(AE_MAXEXPOSURE.Text, 16) >> 8) & 0xff));
                //SetAeRegister("AE_MINEXPOSURE1", ((ulong)Convert.ToInt32(AE_MAXEXPOSURE.Text, 16) & 0xf0));
                if (isWrite) return;

                if (isRead) return;
                if (string.IsNullOrEmpty(txtedit.Text)) return;
                if (XChipAe.Exists(c => c.NameType.ToLower() == txtedit.Name.ToLower() + "_h"))
                {
                    var model = XChipAe.Find(c => c.NameType.ToLower() == (txtedit.Name + "_h").ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, AE_MAXEXPOSURE.Text);
                    SetAeRegister(model, Val);
                }
                if (XChipAe.Exists(c => c.NameType.ToLower() == txtedit.Name.ToLower() + "_l"))
                {
                    var model = XChipAe.Find(c => c.NameType.ToLower() == (txtedit.Name + "_l").ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, AE_MAXEXPOSURE.Text);
                    SetAeRegister(model, Val);
                }

            }
        }

        private void AE_MAXEXPOSURE_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            var txtedit = sender as DevExpress.XtraEditors.TextEdit;
            if (string.IsNullOrEmpty(txtedit.Text)) return;
            var nValue = (Convert.ToUInt32(txtedit.Text, 16) << 4);
            //if (GetCheckListBox(checkedListBoxControl2) == "0") //50hz
            //{

            //    var setFlick50 = GetAERegister("SetFlick50_h") << 8 | GetAERegister("SetFlick50_l");
            //    var temp = (int)((float)nValue / (float)setFlick50 + 0.5) * setFlick50;
            //    SetAeRegister("AE_MAXEXPOSURE_h", (ulong)(temp >> 24));
            //    SetAeRegister("AE_MAXEXPOSURE_m1",(ulong)(temp >> 16 & 0xff));
            //    SetAeRegister("AE_MAXEXPOSURE_m0",(ulong)(temp >> 8 & 0xff));
            //    SetAeRegister("AE_MAXEXPOSURE_l", (ulong)(temp & 0xf0));
            //}
            //else if (GetCheckListBox(checkedListBoxControl2) == "1") //60hz
            //{

            //    var setFlick60 = GetAERegister("SetFlick60_h") << 8 | GetAERegister("SetFlick60_l");
            //    var temp = (int)((float)nValue / (float)setFlick60 + 0.5) * setFlick60;
            //    SetAeRegister("AE_MAXEXPOSURE_h", (ulong)(temp >> 24));
            //    SetAeRegister("AE_MAXEXPOSURE_m1", (ulong)(temp >> 16 & 0xff));
            //    SetAeRegister("AE_MAXEXPOSURE_m0", (ulong)(temp >> 8 & 0xff));
            //    SetAeRegister("AE_MAXEXPOSURE_l", (ulong)(temp & 0xf0));
            //}
            //else
            //{
            //    SetAeRegister("AE_MAXEXPOSURE_h",  (ulong)(Convert.ToInt32(txtedit.Text, 16) >> 24));
            //    SetAeRegister("AE_MAXEXPOSURE_m1", (ulong)(Convert.ToInt32(txtedit.Text, 16) >> 16 & 0xff));
            //    SetAeRegister("AE_MAXEXPOSURE_m0", (ulong)(Convert.ToInt32(txtedit.Text, 16) >> 8 & 0xff));
            //    SetAeRegister("AE_MAXEXPOSURE_l", (ulong)(Convert.ToInt32(txtedit.Text, 16) & 0xf0));
            //}
            SetAeRegister("AE_MAXEXPOSURE_h", (ulong)(Convert.ToInt32(txtedit.Text, 16) >> 24));
            SetAeRegister("AE_MAXEXPOSURE_m1", (ulong)(Convert.ToInt32(txtedit.Text, 16) >> 16 & 0xff));
            SetAeRegister("AE_MAXEXPOSURE_m0", (ulong)(Convert.ToInt32(txtedit.Text, 16) >> 8 & 0xff));
            SetAeRegister("AE_MAXEXPOSURE_l", (ulong)(Convert.ToInt32(txtedit.Text, 16) & 0xf0));
        }

        private void AE_TARGET_JUDGE_TAB0_Leave(object sender, EventArgs e)
        {
            //if (isWrite) return;
            //var txtedit = sender as DevExpress.XtraEditors.TextEdit;
            //if (string.IsNullOrEmpty(txtedit.Text)) return;
            //int i = Convert.ToInt16(txtedit.Tag);

            //uint high = Convert.ToUInt32(txtedit.Text, 16) >> 8;
            //uint low = Convert.ToUInt32(txtedit.Text, 16) & 0xff;
            //SetAeRegister($"AE_TARGET_JUDGE_TAB{2 * i}_Day", high);
            //SetAeRegister($"AE_TARGET_JUDGE_TAB{2 * i + 1}_Day", low);
            //SetAeRegister($"AE_TARGET_JUDGE_TAB{2 * i}_Night", high);
            //SetAeRegister($"AE_TARGET_JUDGE_TAB{2 * i + 1}_Night", low);

            //SetAeRegister($"AE_TARGET_JUDGE_TAB{2 * i}_Day_Set", high);
            //SetAeRegister($"AE_TARGET_JUDGE_TAB{2 * i + 1}_Day_Set", low);
            //SetAeRegister($"AE_TARGET_JUDGE_TAB{2 * i}_Night_Set", high);
            //SetAeRegister($"AE_TARGET_JUDGE_TAB{2 * i + 1}_Night_Set", low);
            if (isWrite) return;

            if (isRead) return;
            var txt = sender as DevExpress.XtraEditors.TextEdit;
            if (string.IsNullOrEmpty(txt.Text)) return;
            //List<string> modelist = new List<string>() { "_Day", "_Night", "_Day_Set", "_Night_Set" };
            //foreach (var item in modelist)
            //{
            //    if (XChipAe.Exists(c => c.NameType.ToLower() == (txt.Name + "_h" + item).ToLower()))
            //    {
            //        var model = XChipAe.Find(c => c.NameType.ToLower() == (txt.Name + "_h" + item).ToLower());
            //        var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
            //        SetAeRegister(model, Val);
            //    }
            //    if (XChipAe.Exists(c => c.NameType.ToLower() == (txt.Name + "_m1" + item).ToLower()))
            //    {
            //        var model = XChipAe.Find(c => c.NameType.ToLower() == (txt.Name + "_m1" + item).ToLower());
            //        var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
            //        SetAeRegister(model, Val);
            //    }
            //    if (XChipAe.Exists(c => c.NameType.ToLower() == (txt.Name + "_m0" + item).ToLower()))
            //    {
            //        var model = XChipAe.Find(c => c.NameType.ToLower() == (txt.Name + "_0m" + item).ToLower());
            //        var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
            //        SetAeRegister(model, Val);
            //    }
            //    if (XChipAe.Exists(c => c.NameType.ToLower() == (txt.Name + "_l" + item).ToLower()))
            //    {
            //        var model = XChipAe.Find(c => c.NameType.ToLower() == (txt.Name + "_l" + item).ToLower());
            //        var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
            //        SetAeRegister(model, Val);
            //    }
            //}
            var item = "_Day";
            if (Mode_switch.EditValue.ToString() == "1")
            {

                if (XChipAe.Exists(c => c.NameType.ToLower() == (txt.Name + "_h" + item).ToLower()))
                {
                    var model = XChipAe.Find(c => c.NameType.ToLower() == (txt.Name + "_h" + item).ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                    SetAeRegister(model, Val);
                }
                if (XChipAe.Exists(c => c.NameType.ToLower() == (txt.Name + "_m1" + item).ToLower()))
                {
                    var model = XChipAe.Find(c => c.NameType.ToLower() == (txt.Name + "_m1" + item).ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                    SetAeRegister(model, Val);
                }
                if (XChipAe.Exists(c => c.NameType.ToLower() == (txt.Name + "_m0" + item).ToLower()))
                {
                    var model = XChipAe.Find(c => c.NameType.ToLower() == (txt.Name + "_0m" + item).ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                    SetAeRegister(model, Val);
                }
                if (XChipAe.Exists(c => c.NameType.ToLower() == (txt.Name + "_l" + item).ToLower()))
                {
                    var model = XChipAe.Find(c => c.NameType.ToLower() == (txt.Name + "_l" + item).ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                    SetAeRegister(model, Val);
                }
            }
            else
            {
                item = "_Night";
                if (XChipAe.Exists(c => c.NameType.ToLower() == (txt.Name + "_h" + item).ToLower()))
                {
                    var model = XChipAe.Find(c => c.NameType.ToLower() == (txt.Name + "_h" + item).ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                    SetAeRegister(model, Val);
                }
                if (XChipAe.Exists(c => c.NameType.ToLower() == (txt.Name + "_m1" + item).ToLower()))
                {
                    var model = XChipAe.Find(c => c.NameType.ToLower() == (txt.Name + "_m1" + item).ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                    SetAeRegister(model, Val);
                }
                if (XChipAe.Exists(c => c.NameType.ToLower() == (txt.Name + "_m0" + item).ToLower()))
                {
                    var model = XChipAe.Find(c => c.NameType.ToLower() == (txt.Name + "_0m" + item).ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                    SetAeRegister(model, Val);
                }
                if (XChipAe.Exists(c => c.NameType.ToLower() == (txt.Name + "_l" + item).ToLower()))
                {
                    var model = XChipAe.Find(c => c.NameType.ToLower() == (txt.Name + "_l" + item).ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                    SetAeRegister(model, Val);
                }
            }
            var OsdDateExist = SerialSend.ReadRegister(0x200011f3, sPortTemp);
            if (GetConfigValue("IsSerial") == "USB" || GetConfigValue("IsI2C") == "1" || OsdDateExist == 0x1)
            {
                if (Mode_switch.EditValue.ToString() == "1")
                {
                    item = "_Day_Set";
                    if (XChipAe.Exists(c => c.NameType.ToLower() == (txt.Name + "_h" + item).ToLower()))
                    {
                        var model = XChipAe.Find(c => c.NameType.ToLower() == (txt.Name + "_h" + item).ToLower());
                        var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                        SetAeRegister(model, Val);
                    }
                    if (XChipAe.Exists(c => c.NameType.ToLower() == (txt.Name + "_m1" + item).ToLower()))
                    {
                        var model = XChipAe.Find(c => c.NameType.ToLower() == (txt.Name + "_m1" + item).ToLower());
                        var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                        SetAeRegister(model, Val);
                    }
                    if (XChipAe.Exists(c => c.NameType.ToLower() == (txt.Name + "_m0" + item).ToLower()))
                    {
                        var model = XChipAe.Find(c => c.NameType.ToLower() == (txt.Name + "_0m" + item).ToLower());
                        var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                        SetAeRegister(model, Val);
                    }
                    if (XChipAe.Exists(c => c.NameType.ToLower() == (txt.Name + "_l" + item).ToLower()))
                    {
                        var model = XChipAe.Find(c => c.NameType.ToLower() == (txt.Name + "_l" + item).ToLower());
                        var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                        SetAeRegister(model, Val);
                    }
                }
                else
                {
                    item = "_Night_Set";
                    if (XChipAe.Exists(c => c.NameType.ToLower() == (txt.Name + "_h" + item).ToLower()))
                    {
                        var model = XChipAe.Find(c => c.NameType.ToLower() == (txt.Name + "_h" + item).ToLower());
                        var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                        SetAeRegister(model, Val);
                    }
                    if (XChipAe.Exists(c => c.NameType.ToLower() == (txt.Name + "_m1" + item).ToLower()))
                    {
                        var model = XChipAe.Find(c => c.NameType.ToLower() == (txt.Name + "_m1" + item).ToLower());
                        var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                        SetAeRegister(model, Val);
                    }
                    if (XChipAe.Exists(c => c.NameType.ToLower() == (txt.Name + "_m0" + item).ToLower()))
                    {
                        var model = XChipAe.Find(c => c.NameType.ToLower() == (txt.Name + "_0m" + item).ToLower());
                        var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                        SetAeRegister(model, Val);
                    }
                    if (XChipAe.Exists(c => c.NameType.ToLower() == (txt.Name + "_l" + item).ToLower()))
                    {
                        var model = XChipAe.Find(c => c.NameType.ToLower() == (txt.Name + "_l" + item).ToLower());
                        var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                        SetAeRegister(model, Val);
                    }
                }
            }

        }
        private string GetConfigValue(string strKey)
        {
            var configFile = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            var settings = configFile.AppSettings.Settings;

            return settings[strKey].Value;
        }
        private void AE_TARGET_JUDGE_THR0_Leave(object sender, EventArgs e)
        {
            //if (Mono_mode_en.Enabled)
            //{
            //    if (isWrite) return;

            //        if (isRead) return;
            //        var txt = sender as DevExpress.XtraEditors.TextEdit;
            //        if (string.IsNullOrEmpty(txt.Text)) return;
            //        string scenesMask = Mono_mode_en.Checked ? "_Night" : "_Day";
            //        if (XChipAe.Exists(c => c.NameType.ToLower() == (txt.Name + "_h" + scenesMask).ToLower()))
            //        {
            //            var model = XChipAe.Find(c => c.NameType.ToLower() == (txt.Name + "_h" + scenesMask).ToLower());
            //            var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
            //            SetAeRegister(model, Val);
            //        }
            //        if (XChipAe.Exists(c => c.NameType.ToLower() == (txt.Name + "_m1" + scenesMask).ToLower()))
            //        {
            //            var model = XChipAe.Find(c => c.NameType.ToLower() == (txt.Name + "_m1" + scenesMask).ToLower());
            //            var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
            //            SetAeRegister(model, Val);
            //        }
            //        if (XChipAe.Exists(c => c.NameType.ToLower() == (txt.Name + "_m0" + scenesMask).ToLower()))
            //        {
            //            var model = XChipAe.Find(c => c.NameType.ToLower() == (txt.Name + "_m0" + scenesMask).ToLower());
            //            var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
            //            SetAeRegister(model, Val);
            //        }
            //        if (XChipAe.Exists(c => c.NameType.ToLower() == (txt.Name + "_l" + scenesMask).ToLower()))
            //        {
            //            var model = XChipAe.Find(c => c.NameType.ToLower() == (txt.Name + "_l" + scenesMask).ToLower());
            //            var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
            //            SetAeRegister(model, Val);
            //        }



            //}
            //else
            //{
            //    if (isWrite) return;

            //        if (isRead) return;
            //        var txt = sender as DevExpress.XtraEditors.TextEdit;
            //        if (string.IsNullOrEmpty(txt.Text)) return;
            //        List<string> modelist = new List<string>() { "_Day", "_Night" };
            //        foreach (var item in modelist)
            //        {
            //            if (XChipAe.Exists(c => c.NameType.ToLower() == (txt.Name + "_h" + item).ToLower()))
            //            {
            //                var model = XChipAe.Find(c => c.NameType.ToLower() == (txt.Name + "_h" + item).ToLower());
            //                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
            //                SetAeRegister(model, Val);
            //            }
            //            if (XChipAe.Exists(c => c.NameType.ToLower() == (txt.Name + "_m1" + item).ToLower()))
            //            {
            //                var model = XChipAe.Find(c => c.NameType.ToLower() == (txt.Name + "_m1" + item).ToLower());
            //                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
            //                SetAeRegister(model, Val);
            //            }
            //            if (XChipAe.Exists(c => c.NameType.ToLower() == (txt.Name + "_m0" + item).ToLower()))
            //            {
            //                var model = XChipAe.Find(c => c.NameType.ToLower() == (txt.Name + "_m0" + item).ToLower());
            //                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
            //                SetAeRegister(model, Val);
            //            }
            //            if (XChipAe.Exists(c => c.NameType.ToLower() == (txt.Name + "_l" + item).ToLower()))
            //            {
            //                var model = XChipAe.Find(c => c.NameType.ToLower() == (txt.Name + "_l" + item).ToLower());
            //                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
            //                SetAeRegister(model, Val);
            //            }
            //        }               
            //}

            if (isWrite) return;

            if (isRead) return;
            var txt = sender as DevExpress.XtraEditors.TextEdit;
            if (string.IsNullOrEmpty(txt.Text)) return;
            var item = "_Day";
            if (Mode_switch.EditValue.ToString() == "1")
            {
                if (XChipAe.Exists(c => c.NameType.ToLower() == (txt.Name + "_h" + item).ToLower()))
                {
                    var model = XChipAe.Find(c => c.NameType.ToLower() == (txt.Name + "_h" + item).ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                    SetAeRegister(model, Val);
                }
                if (XChipAe.Exists(c => c.NameType.ToLower() == (txt.Name + "_m1" + item).ToLower()))
                {
                    var model = XChipAe.Find(c => c.NameType.ToLower() == (txt.Name + "_m1" + item).ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                    SetAeRegister(model, Val);
                }
                if (XChipAe.Exists(c => c.NameType.ToLower() == (txt.Name + "_m0" + item).ToLower()))
                {
                    var model = XChipAe.Find(c => c.NameType.ToLower() == (txt.Name + "_m0" + item).ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                    SetAeRegister(model, Val);
                }
                if (XChipAe.Exists(c => c.NameType.ToLower() == (txt.Name + "_l" + item).ToLower()))
                {
                    var model = XChipAe.Find(c => c.NameType.ToLower() == (txt.Name + "_l" + item).ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                    SetAeRegister(model, Val);
                }
            }
            else
            {
                item = "_Night";
                if (XChipAe.Exists(c => c.NameType.ToLower() == (txt.Name + "_h" + item).ToLower()))
                {
                    var model = XChipAe.Find(c => c.NameType.ToLower() == (txt.Name + "_h" + item).ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                    SetAeRegister(model, Val);
                }
                if (XChipAe.Exists(c => c.NameType.ToLower() == (txt.Name + "_m1" + item).ToLower()))
                {
                    var model = XChipAe.Find(c => c.NameType.ToLower() == (txt.Name + "_m1" + item).ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                    SetAeRegister(model, Val);
                }
                if (XChipAe.Exists(c => c.NameType.ToLower() == (txt.Name + "_m0" + item).ToLower()))
                {
                    var model = XChipAe.Find(c => c.NameType.ToLower() == (txt.Name + "_m0" + item).ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                    SetAeRegister(model, Val);
                }
                if (XChipAe.Exists(c => c.NameType.ToLower() == (txt.Name + "_l" + item).ToLower()))
                {
                    var model = XChipAe.Find(c => c.NameType.ToLower() == (txt.Name + "_l" + item).ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                    SetAeRegister(model, Val);
                }
            }
        }

        private void Factor_Leave(object sender, EventArgs e)
        {
            //if (isWrite) return;
            //if (isRead) return;
            //if (string.IsNullOrEmpty(Factor.Text)) return;
            //var nTemp = Convert.ToUInt32(Factor.Text, 16);
            //var nBHigh = nTemp >> 24;
            //var nHigh = nTemp >> 16 & 0xff;
            //var nMid = nTemp >> 8 & 0xff;
            //var nLow = nTemp & 0xff;
            //SetAeRegister("Factor_h", (ulong)nBHigh);
            //SetAeRegister("Factor_m0", (ulong)nHigh);
            //SetAeRegister("Factor_m1", (ulong)nMid);
            //SetAeRegister("Factor_l", (ulong)nLow);
            if (isWrite) return;

            if (isRead) return;
            var txt = sender as DevExpress.XtraEditors.TextEdit;
            if (string.IsNullOrEmpty(txt.Text)) return;
            string scenesMask = Mode_switch.EditValue.ToString() == "1" ? "_Day" : "_Night";
            if (XChipAe.Exists(c => c.NameType.ToLower() == (txt.Name + "_h").ToLower()))
            {
                var model = XChipAe.Find(c => c.NameType.ToLower() == (txt.Name + "_h").ToLower());
                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                SetAeRegister(model, Val);
            }
            if (XChipAe.Exists(c => c.NameType.ToLower() == (txt.Name + "_m1").ToLower()))
            {
                var model = XChipAe.Find(c => c.NameType.ToLower() == (txt.Name + "_m1").ToLower());
                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                SetAeRegister(model, Val);
            }
            if (XChipAe.Exists(c => c.NameType.ToLower() == (txt.Name + "_m0").ToLower()))
            {
                var model = XChipAe.Find(c => c.NameType.ToLower() == (txt.Name + "_m0").ToLower());
                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                SetAeRegister(model, Val);
            }
            if (XChipAe.Exists(c => c.NameType.ToLower() == (txt.Name + "_l").ToLower()))
            {
                var model = XChipAe.Find(c => c.NameType.ToLower() == (txt.Name + "_l").ToLower());
                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                SetAeRegister(model, Val);
            }



        }

        private void AE_SENSORMAXGAIN_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            if (isRead) return;
            var txtedit = sender as DevExpress.XtraEditors.TextEdit;
            if (string.IsNullOrEmpty(txtedit.Text)) return;
            //注： 这个新写的 数据库中没有
            if (Convert.ToInt32(txtedit.Text, 16) >= 0xffff || Convert.ToInt32(txtedit.Text, 16) < 0)
            {
                if (Convert.ToInt32(txtedit.Text, 16) == 0xffff) return;
                AE_SENSORMAXGAIN.Text = "ffff"; return;
            }
            if (Convert.ToInt32(AE_SENSORMAXGAIN.Text, 16) <= Convert.ToInt32(AE_MAXGAIN.Text, 16))
            {
                //SetAeRegister("AE_SENSORMAXGAIN0", (((ulong)Convert.ToInt32(txtedit.Text, 16) >> 8) & 0xff));
                //SetAeRegister("AE_SENSORMAXGAIN1", ((ulong)Convert.ToInt32(txtedit.Text, 16) & 0xff));
                if (isWrite) return;

                if (isRead) return;
                if (string.IsNullOrEmpty(txtedit.Text)) return;
                if (XChipAe.Exists(c => c.NameType.ToLower() == txtedit.Name.ToLower() + "_h"))
                {
                    var model = XChipAe.Find(c => c.NameType.ToLower() == (txtedit.Name + "_h").ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txtedit.Text);
                    SetAeRegister(model, Val);
                }
                if (XChipAe.Exists(c => c.NameType.ToLower() == txtedit.Name.ToLower() + "_l"))
                {
                    var model = XChipAe.Find(c => c.NameType.ToLower() == (txtedit.Name + "_l").ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txtedit.Text);
                    SetAeRegister(model, Val);
                }

            }
            else
            {
                //SetAeRegister("AE_SENSORMAXGAIN0", (((ulong)Convert.ToInt32(AE_MAXGAIN.Text, 16) >> 8) & 0xff));
                //SetAeRegister("AE_SENSORMAXGAIN1", ((ulong)Convert.ToInt32(AE_MAXGAIN.Text, 16) & 0xff));
                if (isWrite) return;

                if (isRead) return;
                if (string.IsNullOrEmpty(txtedit.Text)) return;
                if (XChipAe.Exists(c => c.NameType.ToLower() == txtedit.Name.ToLower() + "_h"))
                {
                    var model = XChipAe.Find(c => c.NameType.ToLower() == (txtedit.Name + "_h").ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, AE_MAXGAIN.Text);
                    SetAeRegister(model, Val);
                }
                if (XChipAe.Exists(c => c.NameType.ToLower() == txtedit.Name.ToLower() + "_l"))
                {
                    var model = XChipAe.Find(c => c.NameType.ToLower() == (txtedit.Name + "_l").ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, AE_MAXGAIN.Text);
                    SetAeRegister(model, Val);
                }

            }
        }

        private void AE_WIN_WIDTH_X_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                AE_WIN_WIDTH_X_Leave(sender, null);
            }
        }

        private void AE_WIN_HEIGHT_Y_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                AE_WIN_HEIGHT_Y_Leave(sender, null);
            }
        }

        private void AE_BRIGHTNESS_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                AE_BRIGHTNESS_Leave(sender, null);
            }
        }

        private void AE_MAXGAIN_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                AE_MAXGAIN_Leave(sender, null);
            }
        }

        private void AE_MINEXPOSURE_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                AE_MINEXPOSURE_Leave(sender, null);
            }
        }

        private void AE_MAXEXPOSURE_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                AE_MAXEXPOSURE_Leave(sender, null);
            }
        }

        private void AE_SENSORMAXGAIN_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                AE_SENSORMAXGAIN_Leave(sender, null);
            }
        }

        private void AE_TARGET_JUDGE_TAB0_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                AE_TARGET_JUDGE_TAB0_Leave(sender, null);
            }
        }

        private void Factor_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                Factor_Leave(sender, null);
            }
        }

        private void AE_TARGET_JUDGE_THR0_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                AE_TARGET_JUDGE_THR0_Leave(sender, null);
            }
        }

        private void simpleButton6_Click(object sender, EventArgs e)
        {
            //string str = "       设置有效的AE统计窗口，将曝光统计窗口划分为5x5的亮度统计块，可设置每块的权重值，取值范围为0x00~0x40，其值越大对计算平均亮度的影响就会越大；也可勾选“关注区域使能”设置是否将亮度统计块作为关注区域，根据不同的产品运用设置不同关注区域可用于控制收光；权重和关注区域设置后需点击“Refresh”后才能生效。\r\n       Scene_Switch使能后，勾选“调试”可分别调整Day_mode、night_mode、midnight_mode场景下的AE统计窗口和权重值。\r\n       Target_Switch_Mode可通过计算当前Fincal_cal值同Judge_thr设定值进行比较，将对应的Table值映射至“目标亮度”寄存器地址中，其中：\r\n       if (Fincal_cal < Judge_thr[0]) →{Table[0]}\r\n       else if (Fincal_cal < Judge_thr[1]) →{Table[1]}\r\n       else if (Fincal_cal < Judge_thr[2]) →{Table[2]}\r\n       else if (Fincal_cal < Judge_thr[3]) →{Table[3]}\r\n       else if (Fincal_cal < Judge_thr[4]) →{Table[4]}\r\n       else →{Table[5]}\r\n       更多详见《调试工具用户手册》。\r\n";
            //XChip_OptimizationTips ot = new XChip_OptimizationTips("AE调优Tips",str);           
            //ot.StartPosition = FormStartPosition.CenterParent;
            //Task.Run(() =>
            //{
            //    ot.ShowDialog();
            //});
            Thread thread = new Thread(threadPro);
            thread.Start();

        }

        private void threadPro()

        {

            MethodInvoker methodInvoker = new MethodInvoker(ShowFormB);

            BeginInvoke(methodInvoker);

        }

        private void ShowFormB()

        {
            //string str = "\t      \t 设置有效的AE统计窗口，将曝光统计窗口划分为5x5的亮度统计块，可勾选“Area_weight”设置每区域块的权重值，取值范围为0x00~0x40，其值越大对计算平均亮度的影响就会越大，权重值设置后需点击“Refresh”后才能生效。\r\n"
            //   + "\t      \tAvgCal模块在重新触发AE机制中会将64个区域块平均亮度进行由低至高排序，start_blk设定纳入测光统计的起始亮度块，blk_num设定纳入测光统计的亮度块数目，注意：start_blk的值+blk_num的值需≤0x19；且该模块使能与“关注区域”模块使能互斥。\r\n "
            //   + "\t      \t Scene_Switch使能后，勾选“Debug”可分别调整Day_mode、night_mode、midnight_mode场景下的AE统计窗口和权重值。\r\n"
            //   + "\t      \t LFC_Ctrl使能后，可调整“insert_frame_num_max”进行插帧设定，0x10表示插入一帧，0x20表示插入2帧...以此类推。\r\n"
            //   + "\t      \t Target_Judge_Table可通过计算当前Final_cal值同Judge_thr设定值进行比较，将对应的Table值映射至“AE_target”寄存器地址中，其中：\r\n"
            //   + "\t      \t if (Fincal_cal < Judge_thr[0]) →{Table[0]}\r\n"
            //   + "\t      \t else if (Fincal_cal < Judge_thr[1]) →{Table[1]}\r\n"
            //   + "\t      \t else if (Fincal_cal < Judge_thr[2]) →{Table[2]}\r\n"
            //   + "\t      \t else if (Fincal_cal < Judge_thr[3]) →{Table[3]}\r\n"
            //   + "\t      \t else if (Fincal_cal < Judge_thr[4]) →{Table[4]}\r\n"
            //   + "\t      \t else →{Table[5]}\r\n"
            //   + "\t      \t 更多详见《调试工具用户手册》。\r\n";
            string str = "";


            XChip_OptimizationTips ot = new XChip_OptimizationTips("AE调优Tips", str);
            ot.StartPosition = FormStartPosition.CenterScreen;
            //ot.ShowDialog();
            ot.Show();

        }

        private void chk_LFC_en_CheckedChanged(object sender, EventArgs e)
        {
            if (LFC_Ctrl_En.CheckState == CheckState.Checked)
            {
                SetAeRegister("LFC_Ctrl_En", (ulong)0x01);
                insert_frame_num_max.Enabled = nAddExpLine.Enabled = true;
            }
            else
            {
                SetAeRegister("LFC_Ctrl_En", (ulong)0x00);
                insert_frame_num_max.Enabled = nAddExpLine.Enabled = false;
            }
        }

        private void txt_nAddExpLine_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter && !string.IsNullOrEmpty(nAddExpLine.Text))
            {
                var nHigh = Convert.ToUInt32(nAddExpLine.Text, 16) >> 8;
                var nLow = Convert.ToUInt32(nAddExpLine.Text, 16) & 0x00ff;
                SetAeRegister("nAddExpLine_h", (ulong)nHigh);
                SetAeRegister("nAddExpLine_l", (ulong)nLow);
            }
        }

        private void txt_N_Table_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                var txtedit = sender as DevExpress.XtraEditors.TextEdit;
                if (string.IsNullOrEmpty(txtedit.Text)) return;
                int i = Convert.ToInt16(txtedit.Tag);
                SetAeRegister($"AE_TARGET_JUDGE_TAB{2 * i}_Night", (ulong)(Convert.ToInt32(txtedit.Text, 16) >> 8));
                SetAeRegister($"AE_TARGET_JUDGE_TAB{2 * i + 1 }_Night", (ulong)(Convert.ToInt32(txtedit.Text, 16) & 0x00ff));
            }
        }

        private void txt_N_Judge_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                var txtedit = sender as DevExpress.XtraEditors.TextEdit;
                if (string.IsNullOrEmpty(txtedit.Text)) return;
                int i = Convert.ToInt16(txtedit.Tag);
                SetAeRegister($"AE_TARGET_JUDGE_THR{4 * i}_Night", (ulong)(Convert.ToInt32(txtedit.Text, 16) >> 24));
                SetAeRegister($"AE_TARGET_JUDGE_THR{4 * i + 1}_Night", (ulong)(Convert.ToInt32(txtedit.Text, 16) >> 16 & 0xff));
                SetAeRegister($"AE_TARGET_JUDGE_THR{4 * i + 2}_Night", (ulong)(Convert.ToInt32(txtedit.Text, 16) >> 8 & 0xff));
                SetAeRegister($"AE_TARGET_JUDGE_THR{4 * i + 3}_Night", (ulong)(Convert.ToInt32(txtedit.Text, 16) & 0xff));
            }
        }

        private void btn_Refresh_Click(object sender, EventArgs e)
        {
            SetAeRegister("Refresh", 0x01);//SerialSend.WriteRegister( | 0x005a, 0x01, sPortTemp);
        }

        private void chk_Mono_mode_CheckedChanged(object sender, EventArgs e)
        {
            ////DayMonoSwitchLable(Mono_mode_en.Checked);
            ////if (isRead) return;           
            ////var readVal = GetAERegister("Mono_mode_en");
            ////SetAeRegister("Mono_mode_en", (ulong)(Mono_mode_en.Checked ? (readVal | 0x80) : (readVal & 0x7f)));
            //if (isRead) return;
            //if (XChipAe.Exists(c => c.NameType.ToLower() == ($"Mono_mode_en").ToLower()))
            //{
            //    var model = XChipAe.Find(c => c.NameType.ToLower() == ($"Mono_mode_en").ToLower());
            //    var Add = SerialSend.ReadRegister(Convert.ToUInt32(model.Address, 16), sPortTemp);
            //    var Val = BitsHelp.SetBitsCheckedToUint(model.Bits, model.Hex, Add.ToString("X2"), Mono_mode_en.Checked);
            //    SetAeRegister(model, Val);
            //}
            //Mode_switch.SelectedIndex = Mono_mode_en.Checked ? 1 : 0;
            //Mode_switch.Enabled = Mono_mode_en.Checked;
        }

        private void DayMonoSwitchLable(bool isMono)
        {

            if (isMono)
            {
                txt_Judge_thr_0.Text = txt_Judge_thr_0.Text.Replace("normal", "mono");
                txt_Judge_thr_1.Text = txt_Judge_thr_1.Text.Replace("normal", "mono");
                txt_Judge_thr_2.Text = txt_Judge_thr_2.Text.Replace("normal", "mono");
                txt_Judge_thr_3.Text = txt_Judge_thr_3.Text.Replace("normal", "mono");
                txt_Judge_thr_4.Text = txt_Judge_thr_4.Text.Replace("normal", "mono");

                lbl_table_0.Text = lbl_table_0.Text.Replace("normal", "mono");
                lbl_table_1.Text = lbl_table_1.Text.Replace("normal", "mono");
                lbl_table_2.Text = lbl_table_2.Text.Replace("normal", "mono");
                lbl_table_3.Text = lbl_table_3.Text.Replace("normal", "mono");
                lbl_table_4.Text = lbl_table_4.Text.Replace("normal", "mono");
                lbl_table_5.Text = lbl_table_5.Text.Replace("normal", "mono");
            }
            else
            {
                txt_Judge_thr_0.Text = txt_Judge_thr_0.Text.Replace("mono", "normal");
                txt_Judge_thr_1.Text = txt_Judge_thr_1.Text.Replace("mono", "normal");
                txt_Judge_thr_2.Text = txt_Judge_thr_2.Text.Replace("mono", "normal");
                txt_Judge_thr_3.Text = txt_Judge_thr_3.Text.Replace("mono", "normal");
                txt_Judge_thr_4.Text = txt_Judge_thr_4.Text.Replace("mono", "normal");

                lbl_table_0.Text = lbl_table_0.Text.Replace("mono", "normal");
                lbl_table_1.Text = lbl_table_1.Text.Replace("mono", "normal");
                lbl_table_2.Text = lbl_table_2.Text.Replace("mono", "normal");
                lbl_table_3.Text = lbl_table_3.Text.Replace("mono", "normal");
                lbl_table_4.Text = lbl_table_4.Text.Replace("mono", "normal");
                lbl_table_5.Text = lbl_table_5.Text.Replace("mono", "normal");
            }
        }

        private void insert_frame_num_max_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter && !string.IsNullOrEmpty(insert_frame_num_max.Text))
            {
                var nHigh = Convert.ToUInt32(insert_frame_num_max.Text, 16);
                SetAeRegister("insert_frame_num_max", (ulong)nHigh);
            }
        }

        private void start_blk_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter && !string.IsNullOrEmpty(start_blk.Text))
            {
                var nHigh = Convert.ToUInt32(start_blk.Text, 16);
                SetAeRegister("start_blk", (ulong)nHigh);

                switch (AE_radiomode.SelectedIndex)
                {
                    case 0:
                        {

                            SetAeRegister("start_blk_day", (ulong)nHigh);

                            //SerialSend.WriteRegister(, (ulong)(nHigh & 0xff), sPortTemp);
                        }
                        break;
                    case 1:
                        {
                            SetAeRegister("start_blk_night", (ulong)nHigh);
                            //SerialSend.WriteRegister(0x2000145a, (ulong)(nHigh & 0xff), sPortTemp);

                            //SerialSend.WriteRegister(, (ulong)(nHigh & 0xff), sPortTemp);
                        }
                        break;
                    case 2:
                        {
                            SetAeRegister("start_blk_Midnight", (ulong)nHigh);
                            //SerialSend.WriteRegister(0x2000145c, (ulong)(nHigh & 0xff), sPortTemp);


                        }
                        break;
                    default:
                        break;
                }
                //SerialSend.WriteRegister(0x20000240, (ulong)(nHigh & 0xff), sPortTemp);

            }
        }

        private void blk_num_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter && !string.IsNullOrEmpty(blk_num.Text))
            {
                var nHigh = Convert.ToUInt32(blk_num.Text, 16);
                SetAeRegister("blk_num", (ulong)nHigh);
                switch (AE_radiomode.SelectedIndex)
                {
                    case 0:
                        {
                            //备注  数据库里面没有  暂时放地址
                            SetAeRegister("blk_num_day", (ulong)nHigh);
                            //SerialSend.WriteRegister(0x20001459, (ulong)(nHigh & 0xff), sPortTemp);

                            //SerialSend.WriteRegister(, (ulong)(nHigh & 0xff), sPortTemp);
                        }
                        break;
                    case 1:
                        {
                            SetAeRegister("blk_num_night", (ulong)nHigh);
                            //SerialSend.WriteRegister(0x2000145b, (ulong)(nHigh & 0xff), sPortTemp);

                            //SerialSend.WriteRegister(, (ulong)(nHigh & 0xff), sPortTemp);
                        }
                        break;
                    case 2:
                        {
                            SetAeRegister("blk_num_Midnight", (ulong)nHigh);
                            //SerialSend.WriteRegister(0x2000145d, (ulong)(nHigh & 0xff), sPortTemp);

                        }
                        break;
                    default:
                        break;
                }
                //SerialSend.WriteRegister(0x20000241, (ulong)(nHigh & 0xff), sPortTemp);
            }
        }

        private void AE_WEIGHT1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                AE_WEIGHT1_Leave(sender, null);
            }
        }

        private void start_blk_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            start_blk_KeyDown(sender, keyEnter);
        }

        private void blk_num_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            blk_num_KeyDown(sender, keyEnter);
        }

        private void txt_nAddExpLine_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            txt_nAddExpLine_KeyDown(sender, keyEnter);
        }

        private void insert_frame_num_max_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            insert_frame_num_max_KeyDown(sender, keyEnter);
        }

        private void Newmode_en_CheckedChanged(object sender, EventArgs e)
        {

            if (Newmode_en.Checked)
            {
                start_blk.Enabled = true;
                blk_num.Enabled = true;
                //AE_WEIGHTENABLE_EN.CheckState = CheckState.Unchecked;
                SetAeRegister("Newmode_en", 0x1);
                SetAeRegister("avg_calc_en", 0x1);
            }
            else
            {
                start_blk.Enabled = false;
                blk_num.Enabled = false;
                //AE_WEIGHTENABLE_EN.CheckState = CheckState.Checked;
                SetAeRegister("Newmode_en", 0x0);
                SetAeRegister("avg_calc_en", 0x0);
            }


        }

        private async void simpleButton4_Click_1(object sender, EventArgs e)
        {
            if (IsUsbOpen || m_open)
            {

            }
            else
            {
                if (!sPortTemp.IsOpen)
                {
                    DevExpress.XtraEditors.XtraMessageBox.Show("可用端口未打开");
                    return;
                }
            }
            //SerialSend.isDebug = false;
            SaveFileDialog sfd = new SaveFileDialog();
            //设置文件类型 
            sfd.Filter = "配置文件（*.txt）|*.txt";

            //设置默认文件类型显示顺序 
            sfd.FilterIndex = 1;

            //保存对话框是否记忆上次打开的目录 
            sfd.RestoreDirectory = true;
            sfd.FileName = "IQ_Setting_AE_" + DateTime.Now.ToString("yyyyMMddHHmmss");
            if (sfd.ShowDialog() == DialogResult.OK)
            {
                var Pe_dal = new parameter_exportManager();
                if (null != Pe_dal)
                {
                    WaitBefore.Start("参数导出", "正在加载中", 60);
                    //var tempList = Pe_dal.GetList(c => c.Module == "AWB");
                    var tempList = Pe_dal.GetListToExport().Where(c => c.Module == "Area Weight" ||
                    c.Module == "Attention" ||
                    c.Module == "AE Base0" ||
                    c.Module == "AE speed" ||
                    c.Module == "AE speed table" ||
                    c.Module.Contains("avg_weight 0x8014005b") ||
                    c.Module == "Target_table_day" ||
                    c.Module == "Target_table_night" ||
                    c.Module == "Target_judge_thr_day" ||
                    c.Module == "Target_judge_thr_night" ||
                    c.Module.Contains("avg_size 0x80301f00") ||
                    c.Module == "AE window").OrderBy(c => c.SortNum).ToList();
                    #region 判断是否需要用白天的数据
                    var Pe_patch_dal = new parameter_export_patchManager();
                    var patchList = Pe_patch_dal.GetList();
                    var conditionList = tempList.Select(c => c.ConditionAddr).Distinct();
                    foreach (var item in conditionList)
                    {


                        if (await (GetAERegister(item)) == 0)
                        {
                            patchList.RemoveAll(c => c.ConditionAddr == item);
                        }
                    }
                    #endregion
                    var sb = XChipHelp.ReadParameterExportExpand(tempList, "80", patchList, sPortTemp);
                    System.IO.File.WriteAllText(sfd.FileName, sb.ToString());

                }
                WaitBefore.Close();
                DevExpress.XtraEditors.XtraMessageBox.Show("参数导出完成");
            }
        }



        private void simpleButton5_MouseEnter(object sender, EventArgs e)
        {
            isWrite = true;
        }

        private void simpleButton5_MouseLeave(object sender, EventArgs e)
        {
            isWrite = false;
        }

        private async void speed_mode_man_en_CheckedChanged(object sender, EventArgs e)
        {
            var chk = sender as CheckEdit;
            if (isRead) return;
            if (XChipAe.Exists(c => c.NameType.ToLower() == (chk.Name).ToLower()))
            {
                var model = XChipAe.Find(c => c.NameType.ToLower() == (chk.Name).ToLower());
                var Add = await ReadRegisterAsync(model.Address);
                var Val = BitsHelp.SetBitsCheckedToUint(model.Bits, model.Hex, Add.ToString("X2"), chk.Checked);
                await SetAeRegister(model, Val);
            }
            if (chk.Checked)
            {
                SetAeRegister("speed_mode_man", 0x01);
            }
            EnShowHide();
        }

        private void AE_SpeedModeradio_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (isRead) return;
            var aeradio = sender as DevExpress.XtraEditors.RadioGroup;
            if (aeradio.EditValue.ToString() == "1")
            {
                SetAeRegister("speed_mode_man", 0x01);
            }
            else if (aeradio.EditValue.ToString() == "2")
            {
                SetAeRegister("speed_mode_man", 0x02);
            }
            else if (aeradio.EditValue.ToString() == "3")
            {
                SetAeRegister("speed_mode_man", 0x03);
            }
        }

        private void slow_b2d_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            if (null != sPortTemp || !IsUsbOpen || m_open)
            {
                if (isRead) return;
                var txt = sender as DevExpress.XtraEditors.TextEdit;
                if (string.IsNullOrEmpty(txt.Text)) return;

                //if (XChipLenc.Exists(c => c.NameType.ToLower() == txt.Name.ToLower()))
                if (XChipAe.Exists(c => c.NameType.ToLower() == $"{txt.Name.ToLower()}"))
                {
                    var model = XChipAe.Find(c => c.NameType.ToLower() == $"{txt.Name.ToLower()}");
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                    SetAeRegister(model, Val);
                }
            }
        }

        private void slow_b2d_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                slow_b2d_Leave(sender, null);
            }
        }

        private void AE_Flicker_50Hz_Leave(object sender, EventArgs e)
        {
            var txtEdit = sender as DevExpress.XtraEditors.TextEdit;
            if (string.IsNullOrEmpty(txtEdit.Text)) return;

            if (XChipAe.Exists(c => c.NameType.ToLower() == $"{txtEdit.Name}_h".ToLower()))
            {
                var model = XChipAe.Find(c => c.NameType.ToLower() == $"{txtEdit.Name}_h".ToLower());
                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txtEdit.Text);
                SetAeRegister(model, Val);
            }
            if (XChipAe.Exists(c => c.NameType.ToLower() == $"{txtEdit.Name}_l".ToLower()))
            {
                var model = XChipAe.Find(c => c.NameType.ToLower() == $"{txtEdit.Name}_l".ToLower());
                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txtEdit.Text);
                SetAeRegister(model, Val);
            }
        }

        private void AE_Flicker_50Hz_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                AE_Flicker_50Hz_Leave(sender, null);
            }
        }

        private async void Mode_switch_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (Mode_switch.EditValue.ToString() == "1")
            {
                if (isRead) return;
                if (XChipAe.Exists(c => c.NameType.ToLower() == ($"Mono_mode_en").ToLower()))
                {
                    var model = XChipAe.Find(c => c.NameType.ToLower() == ($"Mono_mode_en").ToLower());
                    var Add = await ReadRegisterAsync(model.Address);
                    var Val = BitsHelp.SetBitsCheckedToUint(model.Bits, model.Hex, Add.ToString("X2"), false);
                    await SetAeRegister(model, Val);
                }
                //Table[0]_normal
                lbl_table_0.Text = lbl_table_0.Text.Replace("normal", "").Replace("Gray", "") + "Color";
                lbl_table_1.Text = lbl_table_1.Text.Replace("normal", "").Replace("Gray", "") + "Color";
                lbl_table_2.Text = lbl_table_2.Text.Replace("normal", "").Replace("Gray", "") + "Color";
                lbl_table_3.Text = lbl_table_3.Text.Replace("normal", "").Replace("Gray", "") + "Color";
                lbl_table_4.Text = lbl_table_4.Text.Replace("normal", "").Replace("Gray", "") + "Color";
                lbl_table_5.Text = lbl_table_5.Text.Replace("normal", "").Replace("Gray", "") + "Color";

                txt_Judge_thr_0.Text = txt_Judge_thr_0.Text.Replace("normal", "").Replace("Gray", "") + "Color";
                txt_Judge_thr_1.Text = txt_Judge_thr_1.Text.Replace("normal", "").Replace("Gray", "") + "Color";
                txt_Judge_thr_2.Text = txt_Judge_thr_2.Text.Replace("normal", "").Replace("Gray", "") + "Color";
                txt_Judge_thr_3.Text = txt_Judge_thr_3.Text.Replace("normal", "").Replace("Gray", "") + "Color";
                txt_Judge_thr_4.Text = txt_Judge_thr_4.Text.Replace("normal", "").Replace("Gray", "") + "Color";
               await  UpdateColorGrayAddr();
            }
            else
            {
                if (isRead) return;
                if (XChipAe.Exists(c => c.NameType.ToLower() == ($"Mono_mode_en").ToLower()))
                {
                    var model = XChipAe.Find(c => c.NameType.ToLower() == ($"Mono_mode_en").ToLower());
                    var Add = await ReadRegisterAsync(model.Address);
                    var Val = BitsHelp.SetBitsCheckedToUint(model.Bits, model.Hex, Add.ToString("X2"), true);
                    await SetAeRegister(model, Val);
                }
                lbl_table_0.Text = lbl_table_0.Text.Replace("normal", "").Replace("Color", "") + "Gray";
                lbl_table_1.Text = lbl_table_1.Text.Replace("normal", "").Replace("Color", "") + "Gray";
                lbl_table_2.Text = lbl_table_2.Text.Replace("normal", "").Replace("Color", "") + "Gray";
                lbl_table_3.Text = lbl_table_3.Text.Replace("normal", "").Replace("Color", "") + "Gray";
                lbl_table_4.Text = lbl_table_4.Text.Replace("normal", "").Replace("Color", "") + "Gray";
                lbl_table_5.Text = lbl_table_5.Text.Replace("normal", "").Replace("Color", "") + "Gray";

                txt_Judge_thr_0.Text = txt_Judge_thr_0.Text.Replace("normal", "").Replace("Color", "") + "Gray";
                txt_Judge_thr_1.Text = txt_Judge_thr_1.Text.Replace("normal", "").Replace("Color", "") + "Gray";
                txt_Judge_thr_2.Text = txt_Judge_thr_2.Text.Replace("normal", "").Replace("Color", "") + "Gray";
                txt_Judge_thr_3.Text = txt_Judge_thr_3.Text.Replace("normal", "").Replace("Color", "") + "Gray";
                txt_Judge_thr_4.Text = txt_Judge_thr_4.Text.Replace("normal", "").Replace("Color", "") + "Gray";
               await UpdateColorGrayAddr();
            }
        }
        public async Task UpdateColorGrayAddr()
        {
            isRead = true;
            WaitBefore.Start("读取中", "正在加载中", 10);
            // 记录开始时间和寄存器计数
            var startTime = DateTime.Now;
            int totalRegisterCount = 0;
            string scenesMask = Mode_switch.EditValue.ToString() == "1" ? "_Day" : "_Night";
            long nMask = 0;
            nMask = await GetAERegister("Scene_Switch_En");

            List<string> NameList = new List<string>();

            List<string> NameListsss = new List<string>();

            try
            {
                for (int i = 0; i < XChipAe.Count; i++)
                {

                    var type = AppHelper.NameTypeToString(XChipAe[i].NameType);
                    if (NameList.Exists(c => c.ToLower().Contains(type)))
                    {
                        continue;
                    }
                    if (XChipAe[i].NameType.Contains("AE_WEIGHT_") && !XChipAe[i].NameType.Contains("_EN"))
                    {
                        continue;
                    }
                    try
                    {
                        var col = Controls_Find(type);
                        foreach (var item in col)
                        {
                            //过滤掉指定寄存器
                            if (!item.Name.ToString().ToLower().Contains("AE_TARGET_JUDGE".ToLower()) && !item.Name.ToString().ToLower().Contains("AE_TARGET_JUDGE".ToLower()))
                            {
                                continue;
                            }
                            if (item is TextEdit)
                            {
                                item.Text = "";
                                var nList = XChipAe.Where(c => c.NameType.ToLower().Contains(item.Name.ToString().ToLower()) && c.ControlType == "0").ToList();

                                if (nList.Count == 0)
                                {
                                    nList = XChipAe.Where(c => c.NameType.ToLower().Contains(item.Name.ToString().ToLower()) && c.ControlType == "0").ToList();
                                }

                                if (nList.Count == 1)
                                {
                                    // 单个寄存器读取
                                    var address = nList[0].Address;
                                    totalRegisterCount++;
                                    await ReadRegisterAndUpdateTextAsync(address, item as TextEdit, nList[0].Bits, nList[0].Hex);
                                }
                                else
                                {
                                    // 多个寄存器组合读取 - 特殊处理逻辑
                                    totalRegisterCount += nList.Count;
                                    await ReadMultipleRegistersAndUpdateTextAsync(nList, item as TextEdit, nMask, Mode_switch.SelectedIndex);
                                }
                            }
                            else if (item is CheckEdit)
                            {
                                var nList = XChipAe.Where(c => c.NameType.ToLower().Contains(item.Name.ToString().ToLower()) && c.ControlType == "1").ToList();
                                if (nList.Count == 1)
                                {
                                    var address = nList[0].Address;
                                    totalRegisterCount++;
                                    await ReadRegisterAndUpdateCheckAsync(address, item as CheckEdit, nList[0].Bits, nList[0].Hex);
                                }
                            }



                        }

                        //ae_win_width\ae_win_height 重复名称太多 这里不过滤 数据进行强匹配
                        if (type.ToLower().Contains("ae_win_width") || type.ToLower().Contains("ae_win_height"))
                        {
                            continue;
                        }
                        NameList.Add(type);
                    }
                    catch (Exception)
                    {
                        continue;
                    }
                }
            }
            catch (Exception)
            {
            }
            finally
            {
                isRead = false;
                WaitBefore.Close();
            }
        }




        private void Target_switch_mode_SelectedIndexChanged(object sender, EventArgs e)
        {
            //if (isRead) return;
            //var aeradio = sender as DevExpress.XtraEditors.RadioGroup;
            //if (aeradio.EditValue.ToString() == "1")
            //{
            //    SetAeRegister("speed_mode_man", 0x00);
            //    TargetSwitchEnShowHide(false);
            //}
            //else if (aeradio.EditValue.ToString() == "2")
            //{
            //    SetAeRegister("speed_mode_man", 0x01);
            //    TargetSwitchEnShowHide(true);
            //}
            //else if (aeradio.EditValue.ToString() == "3")
            //{
            //    SetAeRegister("speed_mode_man", 0x02);
            //    TargetSwitchEnShowHide(true);
            //}
        }
        private void EnShowHide()
        {
            if (checkedListBoxControl2.Items[0].CheckState == CheckState.Checked)//50hz
            {
                AE_Flicker_50Hz.Enabled = true;
                AE_Flicker_60Hz.Enabled = false;
            }
            if (checkedListBoxControl2.Items[1].CheckState == CheckState.Checked)//60hz
            {
                AE_Flicker_50Hz.Enabled = false;
                AE_Flicker_60Hz.Enabled = true;
            }
            if ((checkedListBoxControl2.Items[1].CheckState == CheckState.Unchecked) && (checkedListBoxControl2.Items[0].CheckState == CheckState.Unchecked))//均不勾选
            {
                AE_Flicker_50Hz.Enabled = false;
                AE_Flicker_60Hz.Enabled = false;
            }

            slow_b2d.Enabled = speed_mode_man_en.Checked;
            slow_d2b.Enabled = speed_mode_man_en.Checked;

            start_blk.Enabled = Newmode_en.Checked;
            blk_num.Enabled = Newmode_en.Checked;
        }

        private void COMBO_GAMMAPRE_EditValueChanged(object sender, EventArgs e)
        {
            if (isRead) return;
            if (COMBO_GAMMAPRE.EditValue.ToString() == "0")
            {
                SetAeRegister("Target_switch", 0x00);
                TargetSwitchEnShowHide(false);
            }
            else if (COMBO_GAMMAPRE.EditValue.ToString() == "1")
            {
                SetAeRegister("Target_switch", 0x01);
                TargetSwitchEnShowHide(true);
            }
            else if (COMBO_GAMMAPRE.EditValue.ToString() == "2")
            {
                SetAeRegister("Target_switch", 0x02);
                TargetSwitchEnShowHide(true);
            }
        }

        private async void simpleButton8_Click(object sender, EventArgs e)
        {
            //if (IsUsbOpen || m_open)
            //{

            //}
            //else
            //{
            //    if (!sPortTemp.IsOpen)
            //    {
            //        DevExpress.XtraEditors.XtraMessageBox.Show("可用端口未打开");
            //        return;
            //    }
            //}
            var nHigh =await GetAERegister("AE_BRIGHTNESS_h");
            var nLow =await GetAERegister("AE_BRIGHTNESS_l");
            AE_BRIGHTNESS.Text = ((nHigh << 8 & 0xff00) | (nLow & 0xff)).ToString("X4");
        }
    }
}